Pull Last 3 Months

Tim Chase python.list at tim.thechases.com
Wed Oct 17 17:32:48 EDT 2007


> Is there a module that can pull str values for say the last 3 months?
> Something like:
> 
> print lastMonths(3)
> 
> ['Sep', 'Aug', 'Jul']

I don't think there's anything inbuilt.  It's slightly 
frustrating that timedelta doesn't accept a "months" parameter 
when it would be rather helpful (but how many days are in a 
month-delta is something that changes from month-to-month).

It's somewhat inelegant, but this works for me:

   import datetime

   def last_months(months):
     assert months > 0
     d = datetime.date.today()
     m = d.strftime('%b')
     yield m
     while months > 1:
       d -= datetime.timedelta(days=28)
       m2 = d.strftime('%b')
       if m2 <> m:
         m = m2
         months -= 1
         yield m

   print list(last_months(3))
   for month in last_months(24): print month

The alternative would likely be to do something like subtract one 
from the current month, and if it drops below 1, decrement the 
year and reset the month to 12.  Equally fuzzy:

   def lastN(months):
     assert months > 0
     d = datetime.date.today()
     for _ in xrange(months):
       yield d.strftime('%b')
       y,m = d.year, d.month
       if m > 1:
         m -= 1
       else:
         m = 12
         y -= 1
       d = datetime.date(y,m,1)

Use whichever you prefer.

-tkc








More information about the Python-list mailing list