Subtract n months from datetime

Paulo da Silva p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt
Tue Jun 21 00:29:52 EDT 2022


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