Pull Last 3 Months
Shane Geiger
sgeiger at ncee.net
Wed Oct 17 18:56:17 EDT 2007
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
Tim Chase wrote:
>> 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
>
>
>
>
>
>
--
Shane Geiger
IT Director
National Council on Economic Education
sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net
Leading the Campaign for Economic and Financial Literacy
-------------- next part --------------
A non-text attachment was scrubbed...
Name: sgeiger.vcf
Type: text/x-vcard
Size: 310 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20071017/29f569eb/attachment.vcf>
More information about the Python-list
mailing list