Python: Add year(s) with a given date and display the new date
Python Datetime: Exercise-16 with Solution
Write a Python program to add year(s) with a given date and display the new date.
import datetime from datetime import date def addYears(d, years): try: #Return same day of the current year return d.replace(year = d.year + years) except ValueError: #If not same day, it will return other, i.e. February 29 to March 1 etc. return d + (date(d.year + years, 1, 1) - date(d.year, 1, 1)) print(addYears(datetime.date(2015,1,1), -1)) print(addYears(datetime.date(2015,1,1), 0)) print(addYears(datetime.date(2015,1,1), 2)) print(addYears(datetime.date(2000,2,29),1))
2014-01-01 2015-01-01 2017-01-01 2001-03-01
Python Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Python skills with w3resource's quiz
Python: Tips of the Day
Free up Memory:
- Manual garbage collection can be performed on timely or event based mechanism.
import gc collected_objects = gc.collect()
- New Content published on w3resource:
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework