Calculation of elapsed years and elapsed months including leap years

It's not a problem in competitive programming because it depends on the library, but it's a memo.

--Supplement (2020/1/13)

dd = relativedelta(end, begin)
delta_years =  dd.years
delta_months = dd.months

It seems to be okay.

--The following is the previous article

01.01.2000
01.01.2016
From the input
16 years, total 5844 days

I want to get the output. First, it's very easy for days, just subtract datetime.datetime. However, the timedelta obtained by subtracting datetime has days, but not month. In addition, dateimte itself can add days, but cannot add or subtract on a monthly basis.

Solution 1:

Solution 2

Monthly addition and subtraction can be performed by using dateutil.relativedelta. Since this result is saved in datetime, it can be implemented as follows, for example.

import sys
import math
from dateutil.relativedelta import relativedelta

#Input / output processing and 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 are easy to get
dt = e - b
resd = dt.days

#Use relativedelta to get the "month difference"
deltamonth = 0
while True:
    b = b + relativedelta(months=1)
    if b <= e:
        deltamonth += 1
        continue
    break

#The year is always December, so divide it into months and years.
resy = deltamonth // 12
resm = deltamonth % 12


#This is the process of distinguishing between the plural and the singular from the problem
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)

Recommended Posts

Calculation of elapsed years and elapsed months including leap years
[python] Calculation of months and years of difference in datetime
Calculation of homebrew class and existing class
Dealing with "years and months" in Python
Calculation of technical indicators by TA-Lib and pandas
Prepared for date calculation and automation of my bot
Calculation of standard deviation and correlation coefficient in Python
[Python] Types of statistical values (features) and calculation methods