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

tinnews at isbd.co.uk tinnews at isbd.co.uk
Sun Mar 15 19:02:20 CET 2009


Chris Rebert <clp2 at rebertia.com> wrote:
> 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.
> 
I was just hoping there was some calendar object in Python which could
do all that for me (I need the handling of 31st and February etc.)

-- 
Chris Green



More information about the Python-list mailing list