How to add months to a date (datetime object)?
Lorenzo
loluengo at gmail.com
Mon Mar 16 14:03:50 EDT 2009
On Mar 15, 1:28 pm, tinn... 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.
>
> --
> Chris Green
After seeing all this discussion, the best suggestion that comes to my
mind is:
Implement your own logic, and handle special cases as desired, using
calendar.monthrange as a reference to determine if the day really
exists on the new month. i.e.
from datetime import datetime
import calendar
months_to_add = 3
d = datetime.now()
if d.months + months_to_add > 12:
d.replace(year = d.year + (d.months + months_to_add)/12)
d.replace(month = (d.months + months_to_add)%12)
else:
d.replace(month = (d.months + months_to_add))
if d.day > calendar.monthrange(d.year,d.month)[1]:
# do some custom stuff i.e. force to last day of the month or skip
to the next month ....
just my .02
More information about the Python-list
mailing list