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 trialJay Bennett
10,564 PointsStuck on "Harder Time Machine."
I've tried everything I can think of. The script is functioning but it's not returning the right datetime.
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
Courses Plus Student 26,868 PointsYou 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)
Jay Bennett
10,564 PointsThank you!
lindseyk
4,506 PointsHi! 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?
William Li
Courses Plus Student 26,868 PointsHi there, I believe that you can find your answer from this thread. https://teamtreehouse.com/community/python-timemachine-challenge-is-there-a-better-way :)
lindseyk
4,506 PointsOh yes, that was exactly what I was looking for!! Thank you! :)