42
votes

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)

4
This question was already answered here: stackoverflow.com/questions/4039879/… - Dan
This will be easier to answer once you decide just what "the exact number of months" means. A month is not a fixed-length duration; it can vary from 28 to 31 days. Jan 1 and Feb 1 are farther apart than Feb 1 and Mar 1; do you call both intervals "exactly 1 month"? - Keith Thompson
This post nails it! Use dateutil.relativedelta. - srodriguex

4 Answers

26
votes

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

from calendar import monthrange
from datetime import datetime, timedelta

def 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
83
votes

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)
27
votes

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)

6
votes

The advantage of doing it this way is that there are few module dependencies and no looping -- the months can be found by straight calculation.

import datetime as dt

def months_between(date1,date2):
    if date1>date2:
        date1,date2=date2,date1
    m1=date1.year*12+date1.month
    m2=date2.year*12+date2.month
    months=m2-m1
    if date1.day>date2.day:
        months-=1
    elif date1.day==date2.day:
        seconds1=date1.hour*3600+date1.minute+date1.second
        seconds2=date2.hour*3600+date2.minute+date2.second
        if seconds1>seconds2:
            months-=1
    return months

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

date1 = dt.datetime.strptime('2011-08-15 12:00:00', '%Y-%m-%d %H:%M:%S')
date2 = dt.datetime.strptime('2012-02-15 11:59:00', '%Y-%m-%d %X')
print(months_between(date1,date2))
# 5

date2 = dt.datetime.strptime('2012-02-15 12:00:00', '%Y-%m-%d %X')
print(months_between(date1,date2))
# 6

date2 = dt.datetime.strptime('2012-02-15 12:00:01', '%Y-%m-%d %X')
print(months_between(date1,date2))
# 6