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

Jordan Bester
Jordan Bester
4,752 Points

Write a function named time_machine that takes an integer and a string of "minutes", "hours", "days", or "years".

Completely confused on this one? any help on how to solve?

time_machine.py
import datetime
from datetime import timedelta

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

def time_machine(1=minutes, 2=hours, 4=days, 1=years):
  return time_machine(
# 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

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

Stepping through the challenge

# Write a function named `time_machine` that takes an integer and a string..
def time_machine(num, string):
    '''string is one of "minutes", "hours", "days", or "years".
    num is multiple of this unit.
    '''
    # check for each string value and generate the appropriate timedelta
    if string == 'minutes':
        delta = datetime.timedelta(minutes=num)
    if string == 'hours':
        delta = datetime.timedelta(hours=num)
    if string == 'days':
        delta = datetime.timedelta(days=num)
    if string == 'years':
        num = num * 365
        delta = datetime.timedelta(days=num)
    # add this delta to 'starter' and return
    return starter + delta

This can be compresses by building a dictionary of arguments for timedelta:

# Write a function named `time_machine` that takes an integer and a string..
def time_machine(num, string):
    '''string is one of "minutes", "hours", "days", or "years".
    num is multiple of this unit.
    '''
    # adjust num if string is 'years'
    if string == 'years':
        num = num * 365
        # change string to 'days'
        string = 'days'
    # build keyword args
    kwargs = {string: num}
    # create timedelta
    delta = datetime.timedelta(**kwargs)
    # add this delta to 'starter' and return
    return starter + delta

Compressing further to get:

import datetime

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

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