python add one month to a date

Solutions on MaxInterview for python add one month to a date by the best coders in the world

showing results for - "python add one month to a date"
Serena
25 Feb 2017
1import datetime
2import calendar
3
4def add_months(sourcedate, months):
5    month = sourcedate.month - 1 + months
6    year = sourcedate.year + month // 12
7    month = month % 12 + 1
8    day = min(sourcedate.day, calendar.monthrange(year,month)[1])
9    return datetime.date(year, month, day)
10
11# In use:
12>>> somedate = datetime.date.today()
13>>> somedate
14datetime.date(2010, 11, 9)
15>>> add_months(somedate,1)
16datetime.date(2010, 12, 9)
17>>> add_months(somedate,23)
18datetime.date(2012, 10, 9)
19>>> otherdate = datetime.date(2010,10,31)
20>>> add_months(otherdate,1)
21datetime.date(2010, 11, 30)