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

Vlastimil Brom vlastimil.brom at gmail.com
Sun Mar 15 18:47:17 CET 2009


2009/3/15  <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.
>
> --
> Chris Green
> --
> http://mail.python.org/mailman/listinfo/python-list
>

I guess, one can simply do this manually:

>>> td = datetime.date.today()
>>> td
datetime.date(2009, 3, 15)
>>> td_plus_3_months = datetime.date(td.year, td.month+3, td.day)
>>> td_plus_3_months
datetime.date(2009, 6, 15)


however, one have to check for non existing dates:
>>> datetime.date(td.year, td.month+10, td.day)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: month must be in 1..12
>>>

hth
  vbr



More information about the Python-list mailing list