Às 05:44 de 21/06/22, Paul Bryan escreveu:
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
I have a datetime, not a date.
Anyway, the use of calendar.monthrange simplifies the task a lot.

Assuming dtnow has the current datetime and dtn the number of months to be subtracted, here is my solution (the code was not cleaned yet - just a test):
            dtnow_t=list(dtnow.timetuple()[:6]+(dtnow.microsecond,))
            y=dtnow_t[0] # y,m,d,*_=dtnow_t seems slower
            m=dtnow_t[1]
            d=dtnow_t[2]
            dy,dm=divmod(dtn,12)
            y-=dy
            m-=dm
            if m<1:
                m+=12
                y-=1
            daysinmonth=calendar.monthrange(y,m)[1]
            d=min(d,daysinmonth)
            dtnow_t[0]=y
            dtnow_t[1]=m
            dtnow_t[2]=d
            bt=datetime.datetime(*dtnow_t)

Any comments are welcome.

Thank you.
Paulo



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



--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to