Python: Difference of 2 datetimes in months

Tiago Moutinho picture Tiago Moutinho · Aug 10, 2011 · Viewed 61.8k times · Source

Possible Duplicate:
Best way to find the months between two dates (in python)

I would like to know how I can have the exact number of months for this difference:

date1 = datetime.strptime(str('2011-08-15 12:00:00'), '%Y-%m-%d %H:%M:%S')
date2 = datetime.strptime(str('2012-02-15'), '%Y-%m-%d')

date2-date1 results in

datetime.timedelta(183, 43200)

I would like to know the exact number of months, in this case it should return 5 and not 6 (because of the hour)

Answer

sandinmyjoints picture sandinmyjoints · Aug 10, 2011

You could use python-dateutil.

In [4]: from datetime import datetime

In [5]: date1 = datetime.strptime(str('2011-08-15 12:00:00'), '%Y-%m-%d %H:%M:%S')

In [6]: date2 = datetime.strptime(str('2012-02-15'), '%Y-%m-%d')

In [7]: from dateutil import relativedelta

In [8]: r = relativedelta.relativedelta(date1, date2)

In [9]: r
Out[9]: relativedelta(months=-5, days=-30, hours=-12)