Subtract n months from datetime
Paul Bryan
pbryan at anode.ca
Tue Jun 21 00:44:48 EDT 2022
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)
Paul
On Tue, 2022-06-21 at 05:29 +0100, Paulo da Silva wrote:
> Hi!
>
> I implemented a part of a script to subtract n months from datetime.
> Basically I subtracted n%12 from year and n//12 from the month adding
> 12
> months when it goes<=0. Then used try when converting to datetime
> again.
> So, if the day is for example 31 for a 30 days month it raises a
> ValuError exception. Then I subtract 1 to day and repeat.
>
> The code seems too naive and very very complicated!
> What is the best way to achieve this? Any existent module?
>
> At the very end, what I want is to subtract nx where x can be y, m,
> w, d
> for respectively years, months, weeks or days.
>
> I feel I am missing something here ...
>
> Thanks.
> Paulo
>
More information about the Python-list
mailing list