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

Ryan Dyke
Ryan Dyke
5,202 Points

Harder Time Machine - can you pass strings to timedelta?

Instead of making 4 if statements, I'd like to pass time_str ("days", "hours", or "minutes") directly into the timedelta method. Is this possible, or are the quotation marks holding me back form doing so?

time_machine.py
import datetime

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

def time_machine(time_int, time_str):
    if time_str == "years":
        time_int = time_int * 365
        time_str = "days"
        finisher = starter + datetime.timedelta(time_str=time_int)
    else:
        finisher = starter + datetime.timedelta(time_str=time_int)

1 Answer

Steven Parker
Steven Parker
202,108 Points

It looks like you forgot to return the result value!
And the keys in the "key=value" syntax can't be variables, but you can do a little trick with a dictionary literal and the unpacking operator:

def time_machine(time_int, time_str):
    if time_str == "years":
        time_int *= 365
        time_str = "days"
    return starter + datetime.timedelta(**{time_str : time_int})