Calculate the difference between two datetime.date () dates in years and months

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.

+7
source share
3 answers

If you can 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' 
+21
source

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

It is not possible to clearly determine the number of days of difference by year and month; if you define the year as 365 days and the month as 30 days, you can use:

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

Or you could determine the average lengths of the year and month (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) 

In the last calculation, your second difference arises as 11 years and 3 months.

+10
source

timedelta objects do not have information about the months, maybe you better just calculate the years and months

 >>> 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) 
+1
source

All Articles