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

Adam Vasik
Adam Vasik
6,651 Points

I have no idea how to do this please help :(

I have been trying to solve this but my way doesn't work

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)

def time_machine(**kwargs):
    td = datetime.timedelta(**kwargs)
    if 'years' in kwargs:
        tdd = datetime.timedelta(days = 365)
        return starter + (td + (tdd * getattr(other, 'years')
    return starter + td

3 Answers

Pratham Mishra
seal-mask
.a{fill-rule:evenodd;}techdegree
Pratham Mishra
Python Development Techdegree Student 12,695 Points

def time_machine(time_int, years): if years == 'years': time_int = 365 years = 'days' return starter + datetime.timedelta(*{years : time_int})

Steven Parker
Steven Parker
203,990 Points

The function should take a normal argument, you won't need "kwargs".
Another hint: you should also not need "getattr".

Rocket Dollar Invest
Rocket Dollar Invest
6,792 Points

A simple solution for this problem is to first check if the string is 'years' and if so change the string to 'days' since timedelta will not except years as an argument. Then multiply the integer by 365 to get the equivalent number of days for the given number of years. Finally, return the duration as the difference of the starter datetime and the timedelta of the string and integer passed to the method as a literal dictionary with the ** prefix operator to unpack the dictionary.

import datetime

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

def time_machine(integer, string):
    if string == 'years':
        string = 'days'
        integer *= 365
    return starter + datetime.timedelta(**{string: integer})