Using Python standard libraries, i.e. without dateutil or others, and solving the 'February 31st' problem:
import datetime
import calendar
def add_months(date, months):
months_count = months + date.month + months
# Calculate the year
year = date.year + int(months_count / 12)
# Calculate the month
month = (months_count % 12)
if month == 0:
month = 12
# Calculate the day
day = date.day
last_daylast_day_of_month = calendar.monthrange(year, month)[1]
if day > last_daylast_day_of_month:
day = last_daylast_day_of_month
new_date = datetime.date(year, month, day)
return new_date
Testing:
>>>date = datetime.date(2018, 11, 30)
>>>print(date, add_months(date, 3))
(datetime.date(2018, 11, 30), datetime.date(2019, 2, 28))
>>>print(date, add_months(date, 14))
(datetime.date(2018, 12, 31), datetime.date(2020, 2, 29))