Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

Zinia Khondoker
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Zinia Khondoker
Python Development Techdegree Graduate 10,451 Points

Harder Time Machine

Is there a way to solve this using the f string? I've excluded the year for now and just curious to see if this works

time_machine.py
import datetime

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

def time_machine(int, "minutes"or "hours" or "days"):
    timedelta = datetime.timedelta(f'{"minutes"or "hours" or "days"}={int}')
    duration = starter + timedelta
    return duration

1 Answer

Steven Parker
Steven Parker
231,248 Points

First, the declaration needs the second parameter to be a name instead an expression using string literals.

Then, the timedelta needs a keyword and value pair (a "kwarg") instead of a string argument. If you want to get fancy, you can build a dictionary object and then unpack it to create the argument.

When you do make an f-string (in other exercises), you can create a substitution token by surrounding its name with braces. You can also make strings using format() or concatenation.

Gerald Bishop
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Gerald Bishop
Python Development Techdegree Graduate 16,897 Points

I have also tried this f string approach but still cannot figure out how to make it work. My code gives a TypeError. Please help

import datetime

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

def time_machine(integer, string):
    timedelta = datetime.timedelta(f'{string} = {integer}')
    duration = starter + timedelta
    return duration

print(time_machine(5, "minutes"))

# TypeError: unsupported type for timedelta days component: str
Steven Parker
Steven Parker
231,248 Points

Instead of a string, the timedelta should be given a keyword/value pair or an unpacked dictionary.

Also, don't forget you need to handle "years" as a special case.

And, you won't need to print anything for this challenge.