Python: Difference of 2 datetimes in months [duplicate] Python: Difference of 2 datetimes in months [duplicate] python python

Python: Difference of 2 datetimes in months [duplicate]


You could use python-dateutil.

In [4]: from datetime import datetimeIn [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 relativedeltaIn [8]: r = relativedelta.relativedelta(date1, date2)In [9]: rOut[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)


Using calendar module to find out how many days each month has, you can simply count the months.

from calendar import monthrangefrom datetime import datetime, timedeltadef monthdelta(d1, d2):    delta = 0    while True:        mdays = monthrange(d1.year, d1.month)[1]        d1 += timedelta(days=mdays)        if d1 <= d2:            delta += 1        else:            break    return delta