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

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/ErrorandExceptionHandlingGroup(["`Error and Exception Handling`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/FileHandlingGroup -.-> python/with_statement("`Using with Statement`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/numeric_types("`Numeric Types`") python/BasicConceptsGroup -.-> python/strings("`Strings`") python/BasicConceptsGroup -.-> python/type_conversion("`Type Conversion`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/ErrorandExceptionHandlingGroup -.-> python/catching_exceptions("`Catching Exceptions`") python/PythonStandardLibraryGroup -.-> python/date_time("`Date and Time`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-302782{{"`Time Travel Destination Calculator`"}} python/with_statement -.-> lab-302782{{"`Time Travel Destination Calculator`"}} python/variables_data_types -.-> lab-302782{{"`Time Travel Destination Calculator`"}} python/numeric_types -.-> lab-302782{{"`Time Travel Destination Calculator`"}} python/strings -.-> lab-302782{{"`Time Travel Destination Calculator`"}} python/type_conversion -.-> lab-302782{{"`Time Travel Destination Calculator`"}} python/conditional_statements -.-> lab-302782{{"`Time Travel Destination Calculator`"}} python/for_loops -.-> lab-302782{{"`Time Travel Destination Calculator`"}} python/lists -.-> lab-302782{{"`Time Travel Destination Calculator`"}} python/tuples -.-> lab-302782{{"`Time Travel Destination Calculator`"}} python/function_definition -.-> lab-302782{{"`Time Travel Destination Calculator`"}} python/importing_modules -.-> lab-302782{{"`Time Travel Destination Calculator`"}} python/standard_libraries -.-> lab-302782{{"`Time Travel Destination Calculator`"}} python/catching_exceptions -.-> lab-302782{{"`Time Travel Destination Calculator`"}} python/date_time -.-> lab-302782{{"`Time Travel Destination Calculator`"}} python/data_collections -.-> lab-302782{{"`Time Travel Destination Calculator`"}} python/build_in_functions -.-> lab-302782{{"`Time Travel Destination Calculator`"}} end

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']

Summary

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

Other Python Tutorials you may like