0

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.

Tony
  • 1
  • 1
  • What you're looking for is `timedelta` not `relativedelta` – Ahmed I. Elsayed Jun 19 '23 at 14:35
  • 1
    Relative time is always wishy washy. What exactly _is_ "one month"? That's a duration anywhere from 28 to 31 days. Colloquially, any two dates anywhere between 28 and 31 days apart would be called "a month". Same for "one year". Even if it's not exactly 365 days, you'd say "a year". And then what about leap years? There simply is not *correct* answer, and `relativedelta` tries to imitate colloquial or "intuitive" usage. You can dig down into the details if you want to, but I'm not sure why exactly you'd want to… – deceze Jun 19 '23 at 14:42

0 Answers0