3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

閏年を含む経過年数と経過月数の計算

Last updated at Posted at 2020-01-13

ライブラリ依存のため、競技プログラミングでは出る類の問題ではないが、メモ。

  • 補足(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)
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?