14
12

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 3 years have passed since last update.

[python] datetimeの差の月数、年数の算出

Last updated at Posted at 2020-07-18

モチベ

datetime型の加減算をするとtimedelta型が返ってきますが、日より細かい属性しか持っておらず、月や年の計算をするときに毎度つまってググってました。なのでまとめておきます。

コード

・日付と月数の加減により、新たな日付を生成(relativedeltaを使う※timedeltaでは月は扱えない)
・2つの日付の差の月数、年数を求める(monthmodを使う)

# 開始日時をdatetime型で作る  -----------
from datetime import datetime
dt1 = datetime(2018,5,6)  # datetime.datetime(2018, 5, 6, 0, 0)

# 開始日時に任意の月数、日数を加えて新たな日付を生成 -----------
from dateutil.relativedelta import relativedelta
dt2 = start + relativedelta(months=20, days=25)  # datetime.datetime(2020, 1, 31, 0, 0)

# 2つの日付の差を、日単位で求める -----------
dt_dif = (dt2 - dt1)  # datetime.timedelta(days=635)
print(dt_dif.days)  # 635
# print(dt_dif.months)  # errorになります

# 2つの日付の差を、月単位/年単位で求める -----------
from monthdelta import monthmod  # エラー出たら pip install MonthDelta
mmod = monthmod(dt1, dt2)  # (monthdelta(20), datetime.timedelta(days=25)) <-タプル(リストみたいなもん)

## 月数差(余りは切り捨て)
print(mmod[0].months)  # 20

## 年数差(余りは切り捨て)月数差を12で割ります。月の日数は色々ですが、年の月数は常に12なのでこれでok
print(mmod[0].months//12)  # 1

参考

14
12
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
14
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?