[Tutor] Subract Month From Date

Gooch, John John.Gooch at echostar.com
Tue May 3 20:05:50 CEST 2005


Thank you for the idea, I could have been more clear that days part of the
date isn't important. Here is what I came up with:

    currentDate = datetime.datetime.fromtimestamp( time.time() )
    archMonth = 0
    archYear = 0
    if ( currentDate.month == 1 ):
        archMonth = 12
        archYear = currentYear - 1
    else:
        archMonth = currentDate.month -1 
        archYear = currentDate.year
    archDate = datetime.datetime( archYear, archMonth, 1 )#Year/Month of
target files

Even using datetime instead of Date is overkill, but I think this will work
fine in real-world applications. 

Does anyone have a more elegant solution?



-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf
Of Kent Johnson
Sent: Tuesday, May 03, 2005 11:23 AM
Cc: tutor at python.org
Subject: Re: [Tutor] Subract Month From Date


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

_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor


More information about the Tutor mailing list