Pull Last 3 Months

John Machin sjmachin at lexicon.net
Thu Oct 18 02:40:01 CEST 2007


On Oct 18, 8:56 am, 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
>

1. Why use a dict?
2. The if-elif-else caper doesn't scale well; suppose the OP want to
"pull" the previous 6 months. The % operator is your friend.
Try this:

>>> m = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
>>> for mo in range(1, 13):
...    print mo, [m[(mo - x - 2) % 12] for x in range(3)]
...
1 ['Dec', 'Nov', 'Oct']
2 ['Jan', 'Dec', 'Nov']
3 ['Feb', 'Jan', 'Dec']
4 ['Mar', 'Feb', 'Jan']
5 ['Apr', 'Mar', 'Feb']
6 ['May', 'Apr', 'Mar']
7 ['Jun', 'May', 'Apr']
8 ['Jul', 'Jun', 'May']
9 ['Aug', 'Jul', 'Jun']
10 ['Sep', 'Aug', 'Jul']
11 ['Oct', 'Sep', 'Aug']
12 ['Nov', 'Oct', 'Sep']
>>> for mo in range(1, 13):
...    print mo, [m[(mo - x - 2) % 12] for x in range(6)]
...
1 ['Dec', 'Nov', 'Oct', 'Sep', 'Aug', 'Jul']
2 ['Jan', 'Dec', 'Nov', 'Oct', 'Sep', 'Aug']
...snip...
11 ['Oct', 'Sep', 'Aug', 'Jul', 'Jun', 'May']
12 ['Nov', 'Oct', 'Sep', 'Aug', 'Jul', 'Jun']
>>>




More information about the Python-list mailing list