How to Add Months to a Date in Python
Update: Here’s the best way:
download and install the python-dateutil package from http://labix.org/python-dateutil
From the examples on the page here’s the code you would use:
import datetime from dateutil.relativedelta import relativedelta NOW = datetime.datetime.now() NOW + relativedelta(months=+1)
Below is my old, home-brewed method (does seem to work):
You’ll need the mxDateTime module to run it.
import datetime
import mx.DateTime
from math import ceil
def monthify(anint):
if anint%12==0:return 12
else:return anint%12
def add_months_to_date(base_date,number_months):
"""Note: if day in base_date is > highest day in new month
then day become highest day in new month.
base_date can be a datetime.date,datetime.datetime,
or mx.DateTime.Date. We return datetime.datetime"""
base_date=mx.DateTime.Date(base_date.year,base_date.month,base_date.day)
#calculate what year it will be
years_to_add=ceil(
float((number_months-(12-base_date.month)))/float(12))
newyear=base_date.year+max(years_to_add,0)
#calculate new month
newmonth=monthify(base_date.month+number_months)
#calculate new day
max_day=mx.DateTime.Date(newyear,newmonth,1).days_in_month
newday=min(base_date.day,max_day)
#finish up
#new_date=mx.DateTime.Date(newyear,newmonth,newday)
new_date=datetime.datetime(newyear,newmonth,newday)
return new_date
if __name__=="__main__":
#some testing
print add_months_to_date(datetime.date(1999,12,31),2)
print add_months_to_date(datetime.date(1999,12,1),1)
print add_months_to_date(datetime.date(1999,12,1),31)
print add_months_to_date(datetime.datetime(2020,1,1),4)
print add_months_to_date(datetime.datetime(2005,5,3),1)
print add_months_to_date(datetime.datetime(2006,7,27),15)
Update
I have now created this online date calculator to let you add months to a date and more. You can also view its Python source code to see how it works.
And what about using datetime.timedelta ?
today = datetime.datetime.now()
nextMonth = today + datetime.timedelta(months=1)
Good thought, Phil but I get:
>>> today = datetime.datetime.now()“, line 1, in ?
>>> nextMonth = today + datetime.timedelta(months=1)
Traceback (most recent call last):
File “
TypeError: ‘months’ is an invalid keyword argument for this function
Hard work for date manipulation has been done already in:
http://labix.org/python-dateutil
From the examples on the page:
import datetime
from dateutil.relativedelta import relativedelta
NOW = datetime.datetime.now()
NOW + relativedelta(months=+1)
Thanks Waldemar, that does work. It also looks like an excellent package. Well, at the very least I’ve learned an appriciation for adding months today