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)
Use the relativedelta. months + relativedelta. years * 12 formula to get the total months between two dates.
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.
Use df. dates1-df. dates2 to find the difference between the two dates and then convert the result in the form of months.
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With