简体   繁体   中英

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)

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM