How to add months to a date (datetime object)?
clp2 at rebertia.com
Mon Mar 16 00:26:12 CET 2009
On Sun, Mar 15, 2009 at 4:17 PM, Steve Holden <steve at holdenweb.com> wrote:
> Roy Smith 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?"
> OK, suppose I sign a contract on Nov 30 that requires me to make
> quarterly payments. When is my next payment due?
> The use case doesn't seem that unreasonable to me.
Indeed, but the point is that there are likewise reasonable usecases
for the other behaviors too and one should refuse to guess in the face
of ambiguity; the std lib has, merely by default in this case, taken
this to the extreme of not implementing any of them directly.
Somewhat unrelated wish: if only dateutil were in the std lib... Alas!
I have a blog:
More information about the Python-list