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

tinnews at isbd.co.uk tinnews at isbd.co.uk
Sun Mar 15 14:00:50 EDT 2009


Roy Smith <roy at panix.com> wrote:
> In article <49bd3ab8$0$510$bed64819 at news.gradwell.net>, 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. I had a look at
> > the calendar object but that didn't seem to help much.
> 
> Well, before you can "add three months" to something, you need to explain 
> what that means.
> 
> What is Nov 29th plus 3 months?
> 
> What is Jan 31st plus 3 months?
> 
> Months are different lengths.  Asking to "add 3 months" is kind of like 
> asking, "If I'm somewhere in the continental US (east of the Mississippi 
> River) and move three states to the west, how many miles have I moved?"

No, it's perfectly possible applying simple logic.  My reminder
program manages it perfectly well.  I have, for example, two sets of
three monthly reminders.

    One starts on Jan 19th and repeats three monthly, that means Jan
    19th, April 19th, July 19th and October 19th.  Very simple.

    The other is a little more difficult, it starts on December 31st
    and repeats three monthly.  So that one is on December 31st, March
    31st, June 30th and September 30th.

The calendar program manages it perfectly well using what seems to me
fairly obvious logic, what I want is to be able to do the same in
Python. 

I.e. in simple terms I want the "same day N months hence" and, if it
doesn't exist then the nearest possible.

-- 
Chris Green



More information about the Python-list mailing list