|
|
|
|
|
by deathanatos
2306 days ago
|
|
Not with the standard library. (The "timedelta" class only expresses in units up to days, as it is ambiguous how long a month is. There's a nice package called "python-dateutil" that includes a "relativedelta" class; adding a month to March 31 results in April 30: In [7]: datetime.datetime(2020, 3, 31) + dateutil.relativedelta.relativedelta(months=1)
Out[7]: datetime.datetime(2020, 4, 30, 0, 0)
Adding a year to a leap day: In [8]: datetime.datetime(2020, 2, 29) + dateutil.relativedelta.relativedelta(years=1)
Out[8]: datetime.datetime(2021, 2, 28, 0, 0)
The exact duration that relativedelta adds depends on what you add it to. (Hence the name.) But the results tend to match up with human expectations. |
|