In this step, you will learn how to format the past and future dates and return them as a list of strings.
- Inside the
time_travel_destination(time: str, days: int)
function, add the following code to format the past and future dates and return them as a list:
return [past_time.strftime("%d-%m-%Y"), future_time.strftime("%d-%m-%Y")]
The strftime()
method is used to format the past_time
and future_time
datetime.date
objects into strings in the format "dd-mm-yyyy".
- Finally, add an exception handling block to catch any
ValueError
or OverflowError
exceptions that may occur during the function execution:
except (ValueError, OverflowError):
return []
If any of these exceptions are raised, the function will return an empty list.
Your final time_travel_destination(time: str, days: int)
function should look like this:
import datetime
def time_travel_destination(time: str, days: int):
try:
## Extract year, month, and day from the time string
year, month, day = map(int, time.split("-"))
## Check if the date is valid
datetime.date(year, month, day)
try:
## Subtract the specified number of days from the given date
past_time = datetime.date(year, month, day) - datetime.timedelta(days=days)
except OverflowError:
## If an OverflowError occurs, set past_time to the minimum representable date
past_time = datetime.date(1, 1, 1)
## Add the specified number of days to the given date
future_time = datetime.date(year, month, day) + datetime.timedelta(days=days)
## Return the past and future dates in the format 'dd-mm-yyyy'
return [past_time.strftime("%d-%m-%Y"), future_time.strftime("%d-%m-%Y")]
except (ValueError, OverflowError):
## If a ValueError or OverflowError occurs, return an empty list
return []
You have now completed the implementation of the time_travel_destination(time: str, days: int)
function. You can test the function by running the provided examples in the main block of the time_travel_destination.py
file. Some examples are provided below:
print(time_travel_destination('2238-2-11', 30))
print(time_travel_destination('2238-2-11', 0))
print(time_travel_destination('2238-2-11', 100))
['12-01-2238', '13-03-2238']
['11-02-2238', '11-02-2238']
['03-11-2237', '22-05-2238']