Add support for months and years argument in timedelta

Would be excellent feature in my humble opinion:


from datetime import date, timedelta

dt = date(year=2024, month=1, day=29)
dt += timedelta(months=1)
assert dt == date(2024,2,29)

dt = date(year=2024,month=2,day=29)
dt -= timedelta(years=1)
assert dt == date(2023,2,28)

Right now timedelta supports only these arguments:
days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0

If I need to shift month or year it becomes slightly complex to do it alone with standard.

1 Like

You need to exactly specify how your proposal would work, especially with leap days and leap years, and different length months. There are a lot of decisions to be made. Even then, I’m not sure it will be useful enough to be built in to datetime.

You might want to look on PyPI. In particular, dateutil has relativedelta.

1 Like

I don’t think it’s possible to introduce variable length intervals such as months and years to timedelta in a backwards compatible way since that would invalidate the current API contract of timedelta.total_seconds() returning something well-defined, this also includes operations like dividing a timedelta by a number or a timdelta by a timedelta. Those operations would no longer make any sense with a variable length delta.

A timedelta is a fixed interval of time which makes sense independent of the time representation, whereas dateutil.relativedelta only makes sense in the context of date-like and datetime-like objects with separated time components.

3 Likes

Worth noting, in this context, that a timedelta(hours=24) and timedelta(days=1) are equal, and neither actually represents the time from X pm on one day to X pm the next day - both because of daylight savings time and because of leap seconds. But “day” as a span of time is neatly interpretable as exactly 24 times as long as “hour”, even if the Earth’s rotation and government decrees disagree.

Also Pendulum has Duration, which is a subclass of timedela, and supports years and months: Documentation | Pendulum - Python datetimes made easy

Although, as you can imagine, per the documentation:

Even though, it inherits from the timedelta class, its behavior is slightly different

First of all, that’s wrong, 2023 + 1 month != 2024.

What do you actually expect, Feb 29th, 2023?
There’s no such date, 2023 is not a leap year.

Yes sorry for that i meant to shift from 2024. Corrected that