How to add months to a date (datetime object)?

Chris Rebert clp2 at rebertia.com
Sun Mar 15 13:46:53 EDT 2009


On Sun, Mar 15, 2009 at 10:28 AM,  <tinnews at isbd.co.uk> wrote:
> I have a date in the form of a datetime object and I want to add (for
> example) three months to it.  At the moment I can't see any very
> obvious way of doing this.  I need something like:-
>
>    myDate = datetime.date.today()
>    inc = datetime.timedelta(months=3)
>    myDate += inc
>
> but, of course, timedelta doesn't know about months.

Which makes some sense considering a month can range from 28-31 days,
which would make the delta oddly fuzzy.

Here's one approach:
myDate = datetime.date.today()
newYear = myDate.year
newMonth = myDate.month + 3
if newMonth > 12:
    newYear += 1
    newMonth -= 12
inThreeMonths = datetime.date(newYear, newMonth, myDate.day)
#add extra analogous logic if you have to deal with February or 31st days.

Cheers,
Chris

-- 
I have a blog:
http://blog.rebertia.com



More information about the Python-list mailing list