Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Dates and Times in Python Let's Build a Timed Quiz App Simple Time Machine

SUDHARSAN CHAKRAVARTHI
PLUS
SUDHARSAN CHAKRAVARTHI
Courses Plus Student 2,434 Points

datetime

Write a function named delorean that takes an integer. Return a datetime that is that many hours ahead from starter.

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

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

is something wrong in the above code. ?.

Thanks for the guidance.

time_machine.py
import datetime
from datetime import timedelta

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

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

3 Answers

Dan Johnson
Dan Johnson
40,532 Points

You're adding the time delta but you have the hours set negative so you're still going back in time instead of forward.

Drop the negation from inthour and then you'll be set.

SUDHARSAN CHAKRAVARTHI
PLUS
SUDHARSAN CHAKRAVARTHI
Courses Plus Student 2,434 Points

Thank you very much.

But the challenge is to find the hours ahead from starter. So only when we subtract, we will get the time difference hours from starter time. Am i wrong ?. Help me to understand....

Dan Johnson
Dan Johnson
40,532 Points

Since timedeltas represent an amount of time, rather than a specific date, subtracting means moving back in time and addition means moving forward.

Edit: The challenge wants a new datetime returned instead of the difference between those times. Adding or subtracting a timedelta from a datetime object will result in another datetime, if that's what you were confused about.

SUDHARSAN CHAKRAVARTHI
PLUS
SUDHARSAN CHAKRAVARTHI
Courses Plus Student 2,434 Points

Yes. You are right. If the challenge asked for the new time, there will not be any confusion. Thank You very much for the detailed description.