473,473 Members | 1,842 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Pull Last 3 Months

Is there a module that can pull str values for say the last 3 months?
Something like:
print lastMonths(3)

['Sep', 'Aug', 'Jul']

Thanks

Oct 17 '07 #1
11 2432
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

Oct 17 '07 #2
On Oct 17, 9:59 pm, Harlin Seritt <harlinser...@yahoo.comwrote:
Is there a module that can pull str values for say the last 3 months?
Something like:

print lastMonths(3)

['Sep', 'Aug', 'Jul']
You should take a look at the 'datetime' module.

You can get the current month:
datetime.datetime.now().month

And a list of all abbreviated month names:
[datetime.datetime(1900, i + 1, 1).strftime('%b') for i in range(12)]
>From there, it shouldn't be too tricky to construct the list of months
you want.

--
Paul Hankin

Oct 17 '07 #3
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
sg*****@ncee.net | 402-438-8958 | http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy
Oct 17 '07 #4
On Oct 17, 11:56 pm, Shane Geiger <sgei...@ncee.netwrote:
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

Oct 17 '07 #5
Paul Hankin <pa*********@gmail.comwrites:
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)
Heck you don't even need the magic number 12 in there.

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) % len(months)
for i in range(n)]

In general I try to avoid magic numbers: always be explicit about the
semantic purpose of the number, either by binding a meaningful name to
it and only using that reference thereafter, or showing how that value
is derived.

--
\ "I hope some animal never bores a hole in my head and lays its |
`\ eggs in my brain, because later you might think you're having a |
_o__) good idea but it's just eggs hatching." -- Jack Handey |
Ben Finney
Oct 18 '07 #6
On Oct 18, 8:56 am, Shane Geiger <sgei...@ncee.netwrote:
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']
>>>
Oct 18 '07 #7
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)]

Oct 18 '07 #8
On 18/10/2007 10:33 AM, Ben Finney wrote:
Paul Hankin <pa*********@gmail.comwrites:
>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)

Heck you don't even need the magic number 12 in there.

import datetime

months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split()
Heck if you really want to be anal, you could even guard against a typo
(or one of those spaces actually being '\xA0' [seen it happen]) by
adding in here:
MONTHS_IN_YEAR = 12
assert len(months) == MONTHS_IN_YEAR
def last_months(n):
month = datetime.date.today().month
return [months[(month - i - 1) % len(months)
for i in range(n)]

In general I try to avoid magic numbers: always be explicit about the
semantic purpose of the number, either by binding a meaningful name to
it and only using that reference thereafter, or showing how that value
is derived.
It's a bit hard to see how anybody could imagine that in the expression
[months[(month - i - 1) % 12] for i in range(n)]
the number 12 referred to anything but the number of months in a year.
Oct 18 '07 #9
John Machin <sj******@lexicon.netwrites:
It's a bit hard to see how anybody could imagine that in the expression
[months[(month - i - 1) % 12] for i in range(n)]
the number 12 referred to anything but the number of months in a year.
Exactly, that's what people *will* assume. But what if they're wrong,
and you're using the number 12 for some other semantic purpose? If the
programmer has encountered this type of betrayed assumption before,
they'll never be entirely sure that a bare '12' in the code means what
they think it means. And the code doesn't say anything about why the
number was used, so they're left to guess.

Of course, in such a trivial example, it is almost unthinkable that
the number 12 would mean anything else; but the entire point of the
principle of not using magic numbers is that you don't have to wonder
about when that line is crossed.

Better to be explicit about it, in every case, IMO.

--
\ "Money is always to be found when men are to be sent to the |
`\ frontiers to be destroyed: when the object is to preserve them, |
_o__) it is no longer so." -- Voltaire, _Dictionnaire Philosophique_ |
Ben Finney
Oct 18 '07 #10
En Wed, 17 Oct 2007 21:47:50 -0300, Tim Chase
<py*********@tim.thechases.comescribió:
In the event that you need them in whatever your locale is, you
can use the '%b' formatting to produce them:
I prefer the calendar module in that case:

pyimport locale
pylocale.setlocale(locale.LC_ALL, '')
'Spanish_Argentina.1252'
py>
pyimport calendar
pycalendar.month_abbr[12]
'Dic'
pydef prev_months(since, howmany):
.... return [calendar.month_abbr[(since.month-i-2) % 12 + 1] for i in
range(how
many)]
....
pyimport datetime
pyprev_months(datetime.datetime(2005,2,10), 4)
['Ene', 'Dic', 'Nov', 'Oct']
pyprev_months(datetime.datetime(2005,10,17), 3)
['Sep', 'Ago', 'Jul']

--
Gabriel Genellina

Oct 18 '07 #11
On Oct 18, 12:25 am, "Gabriel Genellina" <gagsl-...@yahoo.com.ar>
wrote:
I prefer the calendar module in that case:

pyimport locale
pylocale.setlocale(locale.LC_ALL, '')
'Spanish_Argentina.1252'
py>
pyimport calendar
pycalendar.month_abbr[12]
'Dic'
pydef prev_months(since, howmany):
... return [calendar.month_abbr[(since.month-i-2) % 12 + 1] for i in
range(how
many)]
...
pyimport datetime
pyprev_months(datetime.datetime(2005,2,10), 4)
['Ene', 'Dic', 'Nov', 'Oct']
pyprev_months(datetime.datetime(2005,10,17), 3)
['Sep', 'Ago', 'Jul']
Ah, you beat me to it. I was going to point out that if you're going
to be using month strings, you should use calendar, since it can also
use the correct locale. Plus, it offers a ridiculously simple
solution to this problem compared to all the others.

Hyuga

Oct 18 '07 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Bimo Remus | last post by:
Hi, I am currently taking a C++ class and am having problems with a homework assignment. My problem is that I need to pull the first and last words out of of a character string array which is in...
11
by: Dennis Marks | last post by:
There seems to be a major program with the automatic display of the last modified date. Using the javascript "document.lastModified" sometimes returns the correct date and sometimes 1 Jan 1970...
13
by: SimonC | last post by:
I would like to return data from the last 2 weeks of each given month in Javascript, but in 2 formats. So, the penultimate week (Monday to Sunday) and the last week (Monday to ??) I'm not...
3
by: Melissa | last post by:
I have this table: TblProjectYear ProjectYearID ProjectYearStartDate ProjectYearEndDate The Project Year will always span across December 31; for example 9/1/04 to 6/30/05. How do I build a...
9
by: Robin Tucker | last post by:
Hiya, I need to test "relative dates" in my program, such as "last six months" or "last 3 months" or "in the last week" etc. How can I do this with a DateTime structure? ie. If NodeDate...
5
by: RandyG | last post by:
how do you pull the current months data without having to manually input the date each time?
4
by: sparks | last post by:
We have a new project here, one that I have never tried maybe its easy I don't know yet. We have people that have records dating back over 5 yrs on a sql server. We have to build an access 2003...
3
by: remya1000 | last post by:
i'm using ASP with MSAccess as database. i have two buttons and two textbox in my page. when i press my first button (First month) i need to display the current month in one textbox and last one...
0
by: Harlin Seritt | last post by:
Is there a module that can pull str values for say the last 3 months? Something like: print lastMonths(3) Thanks
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.