datetime: the date of the day one month ago...how?

G

gabor

hi,

i'm trying to get the date of the day one month ago.

for example:

today = 12.apr.2006
one-month-ago = 12.mar.2006

so:

one-month-ago(12.apr.2006) = 12.mar.2006

of course sometimes it gets more complicated, like:

one-month-ago(31.mar.2006)

or

one-month-ago(1.jan.2006)

the datetime.timedelta objects only work with hours or days or weeks,
not month (i understand why)...

but is there a way to calculate this in python?

i really don't want to calculate it by myself :))

thanks,
gabor
 
M

Max M

gabor said:
hi,

i'm trying to get the date of the day one month ago.

for example:

today = 12.apr.2006
one-month-ago = 12.mar.2006

so:

one-month-ago(12.apr.2006) = 12.mar.2006

of course sometimes it gets more complicated, like:

one-month-ago(31.mar.2006)

or

one-month-ago(1.jan.2006)

the datetime.timedelta objects only work with hours or days or weeks,
not month (i understand why)...

but is there a way to calculate this in python?

i really don't want to calculate it by myself :))


It is application specific. So how *do* you want
one-month-ago(31.mar.2006) or one-month-ago(28.feb.2006) to work? No one
can know but you.


--

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science

Phone: +45 66 11 84 94
Mobile: +45 29 93 42 96
 
G

gabor

Max said:
It is application specific. So how *do* you want
one-month-ago(31.mar.2006) or one-month-ago(28.feb.2006) to work? No one
can know but you.

well, give me a solution for ANY behaviour :)

or, let's specify it then:

i want the day that you get by intutively saying "one month ago". means
usually picking the same day in the previous month. if that day does not
exist, i want the nearest day that exist and was BEFORE the nonexistent day.

one-month-ago(31.mar.2006) = 28.feb.2006
one-month-ago(28.feb.2006) = 28.jan.2006


so, now that we have a spec, is there a way to achieve this in python
without writing the algorithm by myself?


thanks,
gabor
 
C

Christos Georgiou

i want the day that you get by intutively saying "one month ago". means
usually picking the same day in the previous month. if that day does not
exist, i want the nearest day that exist and was BEFORE the nonexistent day.

one-month-ago(31.mar.2006) = 28.feb.2006
one-month-ago(28.feb.2006) = 28.jan.2006

def submonth(d):
year, month= d.year, d.month
if month == 1:
year-= 1; month= 12
else:
month-= 1
try:
return d.replace(year=year, month=month)
except ValueError:
return d.replace(day=1) - datetime.timedelta(1)

datetime.date(2006, 1, 28)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top