Pull Last 3 Months

Tim Chase python.list at tim.thechases.com
Thu Oct 18 02:47:50 CEST 2007


> It looks like you copied the month 2 case from the month 1 case
> because you forgot to edit it afterwards. Anyway, a bit of modulo-12
> arithmetic avoids special cases, and allows the number of months to be
> generalised:

nice...

> import datetime
> 
> months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split()
> 
> def last_months(n):
>     month = datetime.date.today().month
>     return [months[(month - i - 1) % 12] for i in range(n)]
> 
> print last_months(3)

In the event that you need them in whatever your locale is, you
can use the '%b' formatting to produce them:

import datetime

month_map = dict(
  (n, datetime.date(2000,n+1,1).strftime('%b'))
  for n in xrange(12)
  )

The function can then be written as either a generator:

def last_months(months):
  this_month = datetime.date.today().month - 1
  for i in xrange(months):
    yield month_map[(this_month-i) % 12]

or as a function returning a list/tuple:

def last_months(months):
  this_month = datetime.date.today().month - 1
  return [month_map[(this_month - i) % 12]
    for i in xrange(months)]




More information about the Python-list mailing list