Strange arithmetic with relativedelta for date calculations

56 views Asked by At

I am using relativedelta to calculate difference between two dates. However, it seems like the year part of the datetime object isn't being recognized. If the dates were of the same year-months, the calculations obtained would make sense.

# lease dates
start = json_obj['lease'][0]['start']
end = json_obj['lease'][0]['end']

print(end, start)
2026-10-31 2020-10-07

startdt = datetime.strptime(start, '%Y-%m-%d')
print(startdt)
2020-10-07 00:00:00 

enddt = datetime.strptime(end, '%Y-%m-%d')
print(enddt)
2026-10-31 00:00:00


# Total months
calc = relativedelta.relativedelta(enddt, startdt)
calc.days
24

calc.months
0
1

There are 1 answers

0
jezrael On BEST ANSWER

There are no months, so calc.months return 0:

# Total months
calc = relativedelta.relativedelta(enddt, startdt)
print (calc)
relativedelta(years=+6, days=+24)

If need all months mutiple years by 12 and add months:

print (calc.months + calc.years * 12)
72