[Tutor] Subract Month From Date

Kent Johnson kent37 at tds.net
Tue May 3 19:23:16 CEST 2005


Gooch, John 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". 

What if it is March 30 or June 31 today?
> 
> 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? 

To just get the month and year you can use datetime and timedelta; just keep subtracting days until 
the month changes:

  >>> import datetime
  >>> t = datetime.datetime.today()
  >>> t
datetime.datetime(2005, 5, 3, 13, 21, 52, 370000)
  >>> oneday = datetime.timedelta(days=1)
  >>> month = t.month
  >>> while t.month == month:
  ...   t -= oneday
  ...
  >>> t
datetime.datetime(2005, 4, 30, 13, 21, 52, 370000)
  >>> t.month
4
  >>> t.year
2005

Kent



More information about the Tutor mailing list