문제

I want to calculate the difference between two datetime.date() dates in years and months.

For example;

d1 = date(2001,5,1)  
d2 = date(2012,1,1)   
d3 = date(2001,1,1)   
d4 = date(2012,5,1)   


diff1 = d2 - d1  
diff2 = d4 - d3

Desired result:

diff1 == 10 years & 8 months. 
diff2 == 11 years & 4 months.

Thanks.

도움이 되었습니까?

해결책

If you are able to install the excellent dateutil package, you can do this:

>>> from dateutil import relativedelta as rdelta
>>> from datetime import date
>>> d1 = date(2001,5,1)
>>> d2 = date(2012,1,1)
>>> rd = rdelta.relativedelta(d2,d1)
>>> "{0.years} years and {0.months} months".format(rd)
'10 years and 8 months'

다른 팁

In python, subtracting two datetime.date objects results in a datetime.timedelta object, which has a days attribute.

Turning the number of days difference into years and months is not clearly defined; if you define a year as 365 days and a month as 30 days, you could use:

years, remainder = divmod(diff1.days, 365)
months = remainder // 30

Or, you could define average year and month lengths to be (slightly) more accurate:

avgyear = 365.2425        # pedants definition of a year length with leap years
avgmonth = 365.2425/12.0  # even leap years have 12 months
years, remainder = divmod(diff1.days, avgyear)
years, months = int(years), int(remainder // avgmonth)

With the latter calculation, your second difference comes out as 11 years and 3 months.

timedelta objects don't have information about months, you might be better to compute the years and months directly

>>> d2.year - d1.year + (d2.month - d1.month)/12,  (d2.month - d1.month)%12
(10, 8)
>>> d4.year - d3.year + (d4.month - d3.month)/12,  (d4.month - d3.month)%12
(11, 4)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top