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

Stuck on "Harder Time Machine."

I've tried everything I can think of. The script is functioning but it's not returning the right datetime.

time_machine.py
import datetime

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

# 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)
def time_machine(n, s):
  td = ()
  if s == "years":
    td = datetime.timedelta(days = (n * 365))
  elif s == "days":
    td = datetime.timedelta(days = n)
  elif s == "hours":
    td = datetime.timedelta(hours = n)
  elif s == "minutes":
    td = datetime.timedelta(minutes = n)
  new_dt = starter - td
  return new_dt

4 Answers

William Li
PLUS
William Li
Courses Plus Student 26,868 Points

You seems to get most of it right, you should add timedelta to starter, not subtract.

def time_machine(num, string):
  if string=="minutes":
    return starter + datetime.timedelta(minutes=num)
  if string=="hours":
    return starter + datetime.timedelta(hours=num)
  if string=="days":
    return starter + datetime.timedelta(days=num)
  if string=="years":
    return starter + datetime.timedelta(days=num*365)

Thank you!

lindseyk
lindseyk
4,506 Points

Hi! Not sure if it's kosher to post a question on top of a question, but I recently finished this challenge as well, and am wondering: Is it possible to pass in a string as an argument (such as "minutes" or "days" in this case), and turn it into a keyword for the timedelta function, so that one does not have to use if, elif, else? Seems sort of redundant to retype for each scenario?

lindseyk
lindseyk
4,506 Points

Oh yes, that was exactly what I was looking for!! Thank you! :)