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

Nicole A
Nicole A
1,790 Points

timedelta

Could someone please tell me how to write the code such that the arguments entered in the time_machine function can be used in the timedelta e.g if string, integer == days, 5, the timedelta should be days = 5.

time_machine.py
import datetime 

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

def time_machine(string,integer):

    from datetime import timedelta

    return starter + timedelta()



# 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)

1 Answer

Steven Parker
Steven Parker
231,236 Points

If you check the Python online documentation for timedelta Objects, you'll see that you can construct one by passing an argument indicating the offset. So for your example (and without any additional imports): datetime.timedelta(days=5). Since your method will receive both the unit name and quantity as arguments, you can use those parameters to select or build the correct statement to use.

The only other trick is that your method needs to handle "years", but since that's not one of the standard offset units some conversion will be required.

Nicole A
Nicole A
1,790 Points

Thank you for taking the time out to explain this Steven.