How to add months to a date (datetime object)?
clp2 at rebertia.com
Sun Mar 15 19:14:18 CET 2009
On Sun, Mar 15, 2009 at 11:00 AM, <tinnews at isbd.co.uk> wrote:
> Roy Smith <roy at panix.com> wrote:
>> In article <49bd3ab8$0$510$bed64819 at news.gradwell.net>, tinnews at isbd.co.uk
>> > 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
> I.e. in simple terms I want the "same day N months hence" and, if it
> doesn't exist then the nearest possible.
But that's not what you said originally; you now fleshed out important
details. Your original question was simpler and more ambiguous.
The problem here is that there are multiple ways to handle the
ambiguous situations and there's no objective, obvious right choice.
Thus, though one must implement it by oneself, one gets exactly the
behavior one desires.
Besides your behavior, one could equally well argue that a 31st repeat
on months without a 31st should just be dropped, or that it should
carry over onto the 1st of the next month (ignoring the complications
of February). Which behavior one needs is completely
I have a blog:
More information about the Python-list