Mg Mogaki
Mg Mogaki

Reputation: 113

Python : Calculate difference between dates in months

I'm trying to find the difference in months between two dates using relativedelta. I'm able to find the difference in years and days but I get 0 when I filter on months. Any suggestions?

from dateutil import relativedelta as rd
import datetime as date 

dateformat = '%Y/%m/%d'
startDate  = date.strptime('2017/07/01',dateformat).date()
endDate = date.strptime('2019/10/29',dateformat).date()

date_diff = rd.relativedelta(endDate,startDate)

print(date_diff.days)

Upvotes: 0

Views: 1652

Answers (3)

tzaman
tzaman

Reputation: 47870

relativedelta shows the difference as years, months, and days. It's not going to show net months if that's what you're looking for. If two dates happen to be on the same month in different years the months attribute will be zero.

If you want to show the total months, you can write a small function that does that for you by adding in the years value.

from datetime import datetime
from dateutil.relativedelta import relativedelta

def month_delta(start_date, end_date):
    delta = relativedelta(end_date, start_date)
    # >>> relativedelta(years=+2, months=+3, days=+28)
    return 12 * delta.years + delta.months

d1 = datetime(2017, 7, 1)
d2 = datetime(2019, 10, 29)
total_months = month_delta(d1, d2)
print(total_months)
# >>> 27

Upvotes: 1

Roushan
Roushan

Reputation: 4440

end-start will produce timedelta object on which days attribute will gve the required days difference

>>> from datetime import date
>>> start = date(2017,7,1)
>>> end = date(2017,11,11)
>>> (end-start).days
133

Upvotes: 0

Paolo Mossini
Paolo Mossini

Reputation: 1096

Here's the solution:

from datetime import datetime

def diff_month(d1, d2):
    return (d1.year - d2.year) * 12 + d1.month - d2.month

assert diff_month(datetime(2010,10,1), datetime(2010,9,1)) == 1
assert diff_month(datetime(2010,10,1), datetime(2009,10,1)) == 12

Upvotes: 1

Related Questions