Python Dates and Times in Python Let's Build a Timed Quiz App Harder Time Machine

Unashe Mutambashora
Unashe Mutambashora
2,483 Points

Increasing a datetime object

How do you increase a single element of a datetime object

time_machine.py
import datetime

starter = datetime.datetime(2015, 10, 21, 16, 29)

def time_machine(integer,string):
    if string == "days":
        return starter + starter.replace( month = 0, day = integer, hour = 0, minute = 0)
    elif string == "minutes":
        return starter + starter.replace( month = 0, day = 0, hour = 0, minute = integer)
    elif string == "hours":
        return starter + starter.replace( month = 0, day = 0, hour = integer, minute = 0)


# Remember, you can't set "years" on a timedelta!
# Consider a year to be 365 days.

## Example
# time_machine(5, "minutes") => datetime(2015, 10, 21, 16, 34)
Myers Carpenter
Myers Carpenter
Treehouse Staff

if you have two variables, dt (a datetime.datetime) and td (a datetime.timedelta) you can add them together and get another datetime.datetime.

https://docs.python.org/3.7/library/datetime.html#timedelta-objects