Time Travel Destination Calculator

PythonPythonBeginner
Practice Now

Introduction

In this project, you will learn how to build a time travel destination calculator using Python. This calculator will help you determine the maximum past and future dates that a time-traveling spaceship can reach based on the current date and the estimated number of days the spaceship can travel.

👀 Preview

## Input:
time_travel_destination('2238-2-11', 30)
time_travel_destination('2238-2-11', 0)
time_travel_destination('2238-2-11', 100)

## Output:
['12-01-2238', '13-03-2238']
['11-02-2238', '11-02-2238']
['03-11-2237', '22-05-2238']

ðŸŽŊ Tasks

In this project, you will learn:

  • How to extract date information from a given string
  • How to calculate the past and future dates based on the given number of days
  • How to format the calculated dates and return them as a list of strings

🏆 Achievements

After completing this project, you will be able to:

  • Understand how to work with dates and timedelta in Python
  • Implement a function to calculate the time travel destination
  • Handle exceptions and edge cases in your code
  • Write clean and maintainable Python code

Extract Date Information

In this step, you will learn how to extract the year, month, and day from the input time string.

  1. Open the time_travel_destination.py file in your preferred code editor.
  2. Locate the time_travel_destination(time: str, days: int) function.
  3. Inside the function, add the following code to extract the year, month, and day from the time parameter:
try:
    ## Extract year, month, and day from the time string
    year, month, day = map(int, time.split("-"))
## except (ValueError, OverflowError):
##     ## If a ValueError or OverflowError occurs, return an empty list
##     return []

This line uses the map() function and the split() method to convert the time string into a list of integers representing the year, month, and day.

  1. Next, you need to check if the extracted date is valid. You can use the datetime.date() function to do this:
## 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)

If the date is valid, this line will not raise any exceptions. If the date is invalid, a ValueError will be raised.

Calculate the Past and Future Dates

In this step, you will learn how to calculate the past and future dates based on the given number of days.

  1. Inside the time_travel_destination(time: str, days: int) function, add the following code to calculate the past and future dates:
try:
    past_time = datetime.date(year, month, day) - datetime.timedelta(days=days)
except OverflowError:
    past_time = datetime.date(1, 1, 1)
future_time = datetime.date(year, month, day) + datetime.timedelta(days=days)

The past_time variable is calculated by subtracting the days parameter from the original date. However, if the resulting date is before the minimum representable date (January 1, 1 AD), an OverflowError will be raised. In this case, we set past_time to the minimum representable date.

The future_time variable is calculated by adding the days parameter to the original date.

Format and Return the Results

In this step, you will learn how to format the past and future dates and return them as a list of strings.

  1. 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".

  1. 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:

  • Input:
print(time_travel_destination('2238-2-11', 30))
print(time_travel_destination('2238-2-11', 0))
print(time_travel_destination('2238-2-11', 100))
  • Output:
['12-01-2238', '13-03-2238']
['11-02-2238', '11-02-2238']
['03-11-2237', '22-05-2238']
âœĻ Check Solution and Practice

Summary

Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.

Other Python Tutorials you may like