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
Lyric Abbott
35,595 PointsBuilding a Math Quiz with Dates and Times in Python
Write a function named delorean that takes an integer. Return a datetime that is that many hours ahead from starter.
my code:
import datetime
starter = datetime.datetime(2015, 10, 21, 16, 29)
function delorean (integer)
return(datetime)
2 Answers
bpietravalle
16,718 PointsHi Lyric, I think the easiest way is to use timedelta. So within your example, perhaps try:
def delorean(integer):
return starter + datetime.timedelta(hours=integer)
One issue of datetime difficult to keep straight for me is that you can't use timedelta on an existing date, because timedelta is an attr of datetime rather than datetime.datetime. so below won't work:
starter.timedelta(hours=integer)
If you wanted to call directly on the date we need to use replace(), for instance:
def delorean(x):
y = starter.hour + x
return starter.replace(hour=y)
Good luck!
Alan Ng
13,368 Pointsfor the last example, only the hour would be replace right?
if you have hour add up greater or equal to 24, then python will give your the ValueError because datetime is formatted.
Jose Luis Lopez
19,179 Pointsimport datetime
starter = datetime.datetime(2015, 10, 21, 16, 29)
def delorean(integer): return starter + datetime.timedelta(hours=integer)
Wolverine .py
2,513 Pointsthanks Luis it worked for me.
Dustin Matlock
33,856 PointsDustin Matlock
33,856 PointsLyric, the topic and title have been updated for relevancy, and so you receive the best response.