473,287 Members | 1,880 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,287 software developers and data experts.

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 2422
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
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...

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.