Why Python relativedelta perform like this?

51 Views Asked by At

I use the following Python to calculate the difference between two dates.

from dateutil.relativedelta import relativedelta
from datetime import datetime

date1 = datetime(2023,3,30)
date2 = datetime(2023,4,30)

delta = relativedelta(date2,date1)

print("Delta years: ",delta.years)
print("Delta months: ", delta.months)
print("Delta days: ",delta.days)

However, there are some weird result when the dates are end date of the month, or in leap year.

date1 date2 result
2023,3,30 2023,4,30 0 year 1 month 0 day
2023,3,31 2023,4,31 0 year 1 month 0 day
2023,2,28 2023,3,31 0 year 1 month 3 days
2024,2,29 2025,2,28 1 year 0 month 0 day

Can anyone explain how relativedelta works on the calculation? (PS: I am beginner without any python knowledge, just know this code because of work)

For example, why the first two examples have same result? Also, if relativedelta ignore day difference when both are end of month, why example 3 is not 1 month only.

0

There are 0 best solutions below