Pull Last 3 Months

Paul Hankin paul.hankin at gmail.com
Wed Oct 17 19:53:22 EDT 2007


On Oct 17, 11:56 pm, Shane Geiger <sgei... at ncee.net> wrote:
> A simpler way, imho:
>
> import datetime
> m = {
> 1:'Jan',2:'Feb',3:'Mar',4:'Apr',5:'May',6:'Jun',7:'Jul',8:'Aug',9:'Sep',10:'Oct',11:'Nov',12:'Dec'}
>
> month = datetime.date.today().month
> if month == 1:
>     ans = [m[11], m[12], m[1]]
> elif month == 2:
>     ans = [m[11], m[12], m[1]]
> else:
>     ans = [m[month-2], m[month-1], m[month]]
> print ans

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:

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)

--
Paul Hankin




More information about the Python-list mailing list