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

Khaleel Yusuf
Khaleel Yusuf
13,528 Points

Write a function named time_machine that takes an integer and a string of "minutes", "hours", "days", or "years". This d

I need so much help.

time_machine.py
import datetime

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

# Remember, you can't set "years" on a timedelta!
# Consider a year to be 365 days.

## Example
# time_machine(5, "minutes") => datetime(2015, 10, 21, 16, 34)

6 Answers

Logan R
Logan R
22,557 Points

Hi!

This challenge took me a second to understand as well when I did it, so no worries.

What it's really saying is that they are going to give you a number and a unit of time. It wants you to add that much time to the starter variable. So let's say that starter is today and I pass in 5 and days. It wants you to return the starter date plus 5 days.

So IE:

starter = ...

def time_machine(time, units):
    if units == "days":
        return datetime.timedelta(days=time) + starter
    ......

time_machine(5, "days")       # Returns the "starter" date + 5 days.

Hopefully this helps you out!

Khaleel Yusuf
Khaleel Yusuf
13,528 Points

What do the 6 dots mean?

Logan R
Logan R
22,557 Points

The dots are just a way to say that there's more code that just isn't shown.

Khaleel Yusuf
Khaleel Yusuf
13,528 Points

Well, I don't know what to write next.

Logan R
Logan R
22,557 Points

You need to look at each unit case ("minutes", "hours", "days", and "years") and return the appropriate time delta for each one. In the example code I posted in the original answer, it already has "days" completed.

Logan R
Logan R
22,557 Points

Can you paste in the code you tried to run that didn't work?

Khaleel Yusuf
Khaleel Yusuf
13,528 Points
import datetime

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

def time_machine(time, units):
    if units == "days":
        return datetime.timedelta(days=time) + starter
    else if units == "minutes":
        return datetime.timedelta(minutes=time) + starter
    else if units == "hours":
        return datetime.timedelta(hours=time) + starter

time_machine(5, "days") 
Logan R
Logan R
22,557 Points

So you're pretty close. You still need to add the years block, the else if should be elif, and you don't need to call the time_machine (5, "days"). It will call it automatically. I just added that as an example for what it would look like to call the function.

You're almost there ;) Just don't forget that there is no years for timedelta. You need to use days and multiply by 365!