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 Dates and Times in Python (2014) Let's Build a Timed Quiz App Simple Time Machine

Welser Muñoz
Welser Muñoz
4,447 Points

Simple Time Machine

Hi, I have a doubt!, I don't really understand what you are asking me the question.

time_machine.py
import datetime

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

def delorean(a):
  now = datetime.datetime.now()
  diff = starter - now
  seconds = diff.total_seconds()
  hours = round(seconds/3600)
  return hours

3 Answers

Dan Johnson
Dan Johnson
40,533 Points

This challenge is showing the use of timedelta objects. timedeltas let you treat date and times more like basic numeric types. You can add or subtract them to move forward or back in time. For example:

import datetime

starter = datetime.datetime(2015, 10, 21, 16, 29)
delta = datetime.timedelta(hours=1)

one_hour_ahead = starter + delta

print(one_hour_ahead)

Will print out:

2015-10-21 17:29:00

So to use this in the challenge you'll want to make a function that can take one argument that represents how many hours someone wants to move ahead from the starter date, and return that new date.

to simplify:

import datetime

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

def delorean(num):
    return starter.replace(hour = starter.hour + num)