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

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

http://teamtreehouse.com/library/dates-and-times-in-python/lets-build-a-math-quiz-app/simple-time-machine

Lyric, the topic and title have been updated for relevancy, and so you receive the best response.

2 Answers

Hi 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!

for 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.

import datetime

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

def delorean(integer): return starter + datetime.timedelta(hours=integer)

thanks Luis it worked for me.