[Tutor] Subract Month From Date

Karl Pflästerer sigurd at 12move.de
Tue May 3 20:40:11 CEST 2005


On  3 Mai 2005, John.Gooch at echostar.com wrote:

> What would be the simplest way to extract the Month and Year for one month
> prior to the current month? I have been looking for a way to create a Date
> object with the current date, and then subtract a month from it. Say it is
> currently "January 1st, 2005", I would like to be able to subtract a month
> and get "December 1, 2004". 
>
> For the code I am working with I am only interested in the Month and the
> Year. Is there a way to use datetime or date modules to do this? Or perhaps
> I need to use a different module? 


You could use the datetime module, create a date object use a function
to subtract the months.


import datetime as dt
dat = dt.date.today()

def subtract_date(date, year=0, month=0):
    year, month = divmod(year*12 + month, 12)
    if date.month <= month:
        year = date.year - year - 1
        month = date.month - month + 12
    else:
        year = date.year - year
        month = date.month - month
    return date.replace(year = year, month = month)

e.g.

>>> for i in range(10):
...     print subtract_date(dat, month=i)
... 
2005-05-03
2005-04-03
2005-03-03
2005-02-03
2005-01-03
2004-12-03
2004-11-03
2004-10-03
2004-09-03
2004-08-03


Instead you could create a timedelta object from the number of months or
years and subtract it from the date.  The problem is that you have to
convert your months to days; so you have to know the number of days of
each of the months you want to subtract.  The above approach (which only
works with your simple needs) doesn't need that information.


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


More information about the Tutor mailing list