add 3 years to a given date in python code

Solutions on MaxInterview for add 3 years to a given date in python code by the best coders in the world

showing results for - "add 3 years to a given date in python code"
María Fernanda
20 Feb 2018
1import datetime
2from datetime import date
3def addYears(d, years):
4    try:
5#Return same day of the current year        
6        return d.replace(year = d.year + years)
7    except ValueError:
8#If not same day, it will return other, i.e.  February 29 to March 1 etc.        
9        return d + (date(d.year + years, 1, 1) - date(d.year, 1, 1))
10
11print(addYears(datetime.date(2015,1,1), -1))
12print(addYears(datetime.date(2015,1,1), 0))
13print(addYears(datetime.date(2015,1,1), 2))
14print(addYears(datetime.date(2000,2,29),1))
15
16