Subtract n months from datetime

Dan Stromberg drsalists at gmail.com
Tue Jun 21 10:06:15 EDT 2022


On Mon, Jun 20, 2022 at 9:45 PM Paul Bryan <pbryan at anode.ca> wrote:

> Here's how my code does it:
>
>
> import calendar
>
> def add_months(value: date, n: int):
>   """Return a date value with n months added (or subtracted if
> negative)."""
>   year = value.year + (value.month - 1 + n) // 12
>   month = (value.month - 1 + n) % 12 + 1
>   day = min(value.day, calendar.monthrange(year, month)[1])
>   return date(year, month, day)
>

This looks interesting.

You also could add or subtract the average number of seconds in a month:
2629743.75

This has the strange property that the time of day, or even calendar day,
could change. However, it is round-trippable.


More information about the Python-list mailing list