Subtract n months from datetime
Richard Damon
Richard at Damon-Family.org
Tue Jun 21 07:59:59 EDT 2022
On 6/21/22 12:29 AM, 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
>
The biggest issue with "subtracting months" is getting the right
definition of what you mean by that, especially in the corner cases,
once that is established, programming it is fairly easy.
The problem is that a month isn't a fixed unit of time, but is a period
anywhere from 28 to 31 days. (you get the same problem for years, but
the difference is more special case, the presence or absent of Feb 29th.)
The normal definition of this operation has the strange property that if
you subtract a month, then add a month, you sometimes don't get back to
the same day as you started with. Also subtracting one month, and then
subtracting another month might get you a different day than subtracting
2 months at once (Think of Mar 31st).
In short, this sort of date operation IS hard, and application specific,
so while there may be pre-built modules that have this operation, you
need to see if it uses a compatible definition of what you want.
One alternative, which breaks other expectations, is to think of a month
as 30 or 30.5 (so 2 months are 61 days) days, and add that. It says that
often a month later than a given day isn't the same day of the month,
but does make some operations less surprising. (This is hard to do to a
date expressed as year-month-day, but trivial in some other formats like
a timestamp.)
--
Richard Damon
More information about the Python-list
mailing list