w3resource

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.

Sample Solution:

Python Code:

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))

Sample Output:

2014-01-01                                                                                                    
2015-01-01                                                                                                    
2017-01-01                                                                                                    
2001-03-01

Flowchart:

Flowchart: Add year(s) with a given date and display the new date.

Python Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Python program to select all the Sundays of a specified year.
Next: Write a Python program to drop microseconds from datetime.

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()