Using Python Datetime module to calculate the next year when a user-input date will occur by factoring in the leap year. The code has an error

This program is supposed to take the date_string parameter in the format of "year-month-day", and use the add_year function to calculate the next year that this date will occur (it's 4 years later for the 29th of February during Leap Year, and 1 year later for all other dates).

There's an error in the code which is resulting in the wrong answer. Instead of the actual date in the result, the code generates "yyyy-mm-dd" every single time.

import datetime
from datetime import date
def add_year(date_obj): try: new_date_obj = date_obj.replace(year = date_obj.year + 1) except ValueError: # This gets executed when the above method fails, # which means that we're making a Leap Year calculation new_date_obj = date_obj.replace(year = date_obj.year + 4) return new_date_obj
def next_date(date_string): # Convert the argument from string to date object date_obj = datetime.datetime.strptime(date_string, r"%Y-%m-%d") next_date_obj = add_year(date_obj) # Convert the datetime object to string, # in the format of "yyyy-mm-dd" next_date_string = next_date_obj.strftime("yyyy-mm-dd") return next_date_string
today = date.today() # Get today's date
print(next_date(str(today)))
# Should return a year from today, unless today is Leap Day
print(next_date("2021-01-01")) # Should return 2022-01-01
print(next_date("2020-02-29")) # Should return 2024-02-29
4

1 Answer

import datetime
from datetime import date
def add_year(date_obj): try: new_date_obj = date_obj.replace(year = date_obj.year + 1) except ValueError: # This gets executed when the above method fails, # which means that we're making a Leap Year calculation new_date_obj = date_obj.replace(year = date_obj.year + 4) return new_date_obj
def next_date(date_string): # Convert the argument from string to date object date_obj = datetime.datetime.strptime(date_string, r"%Y-%m-%d") next_date_obj = add_year(date_obj) # Convert the datetime object to string, # in the format of "yyyy-mm-dd" next_date_string = next_date_obj.strftime("%Y-%m-%d") return next_date_string
today = date.today() # Get today's date
print(next_date(str(today)))
# Should return a year from today, unless today is Leap Day
print(next_date("2021-01-01")) # Should return 2022-01-01
print(next_date("2020-02-29")) # Should return 2024-02-29
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like