Welcome, guest | Sign In | My Account | Store | Cart

The datetime module only accepts inputs of time it understands. For example, the months given to it have to be in range of values 1-12. This wrapper works around that issue and enables you to move forward or backward more arbitrary units of time. It does that by changing the year, month, and day to fit the requirements of datetime.

Python, 21 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import datetime

def get_date(yr,mth,day):
        if mth<1:
            yr=yr-((abs(mth)/12)+1)
            mth=mth+((abs(mth)/12)+1)*12
        if mth>12:
            yr=yr+(mth/12)
            mth=mth-(mth/12)*12

        begin_mth= datetime.date(yr, mth, 1)
        return begin_mth + datetime.timedelta(day - 1)

today = datetime.date.today()
print 'now\t\t\t',get_date(today.year, today.month, today.day)
print '36 mths ago\t\t',get_date(today.year, today.month-36, today.day)
print '35 mths ago\t\t',get_date(today.year, today.month-35, today.day)
print '36 mths from now\t',get_date(today.year, today.month+36, today.day)
print '35 mths from now\t',get_date(today.year, today.month+35, today.day)
print '50 days ago\t\t',get_date(today.year, today.month, today.day-50)
print '2 years ago\t\t',get_date(today.year-2, today.month, today.day)

If you want to do something like: "go back 36 months from this date", you cannot use -36 as input to datetime for months. It only accepts values from 1 to 12. This simple wrapper converts a time change you give it to a time that datetime will accept for you, so you can use -36 as input.

today = datetime.date.today() The following line would fail with: "ValueError: month must be in 1..12". print '36 mths ago', datetime.date(today.year, today.month-36, today.day)

with get_date it succeeds:

print '36 mths ago\t\t',get_date(today.year, today.month-36, today.day)

1 comment

Harald Armin massa 19 years, 7 months ago  # | flag

Did you look at the various dateutils present? There are some libraries atop of datetime...

especially

https://moin.conectiva.com.br/DateUtil

with Gustavo Niemeyer

and

http://www.voidspace.org.uk/atlantibots/pythonutils.html#dateutils

with Michael Foord

(please note also the powerfull python on his site)

Harald