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

SUDHARSAN CHAKRAVARTHI
PRO
SUDHARSAN CHAKRAVARTHI
Pro 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,520 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
PRO
SUDHARSAN CHAKRAVARTHI
Pro 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,520 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
PRO
SUDHARSAN CHAKRAVARTHI
Pro 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.