Nesta etapa, você aprenderá como formatar as datas no passado e no futuro e retorná-las como uma lista de strings.
- Dentro da função
time_travel_destination(time: str, days: int), adicione o seguinte código para formatar as datas no passado e no futuro e retorná-las como uma lista:
return [past_time.strftime("%d-%m-%Y"), future_time.strftime("%d-%m-%Y")]
O método strftime() é usado para formatar os objetos datetime.date past_time e future_time em strings no formato "dd-mm-yyyy".
- Finalmente, adicione um bloco de tratamento de exceção para capturar quaisquer exceções
ValueError ou OverflowError que possam ocorrer durante a execução da função:
except (ValueError, OverflowError):
return []
Se alguma dessas exceções for levantada, a função retornará uma lista vazia.
Sua função final time_travel_destination(time: str, days: int) deve ser semelhante a esta:
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 []
Você concluiu a implementação da função time_travel_destination(time: str, days: int). Você pode testar a função executando os exemplos fornecidos no bloco principal do arquivo time_travel_destination.py. Alguns exemplos são fornecidos abaixo:
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']