ライブラリ依存のため、競技プログラミングでは出る類の問題ではないが、メモ。
- 補足(2020/1/13)
dd = relativedelta(end, begin)
delta_years = dd.years
delta_months = dd.months
でいいらしいです。
- 以下、前の記事
01.01.2000
01.01.2016
という入力から
16 years, total 5844 days
という出力を得たい。まず、daysに関しては非常に容易で、datetime.datetimeを引き算すればよい。
ただ、datetimeの引き算で得られるtimedeltaはdaysを持つものの、monthは持たない。
加えて、dateimte自身も、daysの足し算はできるものの、月単位の加減算はできない。
解法1:
解法2
dateutil.relativedelta
をつかうことで、月単位の加減算を行える。この結果はdatetimeに保存されるので、例えば、以下のように実装できる。
import sys
import math
from dateutil.relativedelta import relativedelta
# 入出力処理とdatetime化
import datetime
begin = input()
end = input()
bd, bm, by = map(int, begin.split("."))
b = datetime.datetime(year=by, month=bm, day=bd)
ed, em, ey = map(int, end.split("."))
e = datetime.datetime(year=ey, month=em, day=ed)
# delta daysは簡単に得られる
dt = e - b
resd = dt.days
# relativedeltaを使い、「月の差分」を得る
deltamonth = 0
while True:
b = b + relativedelta(months=1)
if b <= e:
deltamonth += 1
continue
break
# 年は必ず12月なので、月と年に分ける。
resy = deltamonth // 12
resm = deltamonth % 12
# ここは問題より複数形と単数形を区別する処理
res = ""
if resy > 0:
if resy == 1:
res += "1 year, "
else:
res += "{0} years, ".format(resy)
if resm > 0:
if resm == 1:
res += "1 month, "
else:
res += "{0} months, ".format(resm)
if resd == 1 or resd == 0:
res += "total {0} days".format(resd)
else:
res += "total {0} days".format(resd)
print(res)