Hacker News new | ask | show | jobs
by perl4ever 2298 days ago
What if you take March 31st and add one month to it? (I assume you can do that somehow)
2 comments

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.
You get April 30. Idk about all libraries, but date-fns and few others I worked with do it right.

Also, if you add one month to Apr 30 and two months to Mar 31, you’ll see that month addition is not commutative-y and one should operate on distances from a base date, not in an incremental way.