Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Difference of 2 datetimes in months [duplicate]

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)

like image 1000
Tiago Moutinho Avatar asked Aug 10 '11 18:08

Tiago Moutinho


People also ask

How do I find the difference in months between two dates in Python?

Use the relativedelta. months + relativedelta. years * 12 formula to get the total months between two dates.

How do I get the difference between two Datetimes in Python?

Use the strptime(date_str, format) function to convert a date string into a datetime object as per the corresponding format . To get the difference between two dates, subtract date2 from date1.

How do you calculate month difference between two dates in pandas?

Use df. dates1-df. dates2 to find the difference between the two dates and then convert the result in the form of months.


2 Answers

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) 
like image 99
sandinmyjoints Avatar answered Sep 21 '22 09:09

sandinmyjoints


Only you know the requirements you must meet, but the fact that there are 183 days and 43200 SI seconds between these two dates highlights an inherent subjectivity in determining how many months that "really" is.

Is a month 30 days, or (365 / 12) days, or ((365 * 4 + 1) / 48) days, or ...?

Is a day always 86400 seconds, or do you count historical leap seconds, or do you predict leap seconds for future dates?

These decisions affect the answer the algorithm you appear to desire will give you for certain input dates that are close to these boundaries.

In my opinion, it is more intuitive to consider months as atomic units of time for this purpose and use this formula: (date2.year - date1.year) * 12 + (date2.month - date1.month)

like image 30
wberry Avatar answered Sep 20 '22 09:09

wberry