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 Harder Time Machine

Better way to pass this Python Code Challenge?

I have a feeling my if statement is too verbose (and probably other parts too). Any suggestions for improving the code?

time_machine.py
import datetime

starter = datetime.datetime(2015, 1, 1, 0, 0)

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

def time_machine(time_length, time_units):
    if time_units == "years":
        num_days = time_length * 365
    elif time_units == "days":
        num_days = time_length
    elif time_units == "hours":
        num_days = time_length / 24
    else: 
        num_days = time_length / 1440

    return starter + datetime.timedelta(days=num_days)

2 Answers

Ken Alger
STAFF
Ken Alger
Treehouse Teacher

Mr. Carson;

If you take a look at this post you can see a solution utilizing Python's timedelta function more often in the code. Personally I like the way you did it as it is more readable, but that could just be my personal preference.

Happy coding,

Ken

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

Hmm, interesting that you went with time_length always being days and then divided it to get minutes and seconds. I never considered that solution. I don't see a problem with you having that many if and elif conditions. We don't have a switch in Python, so this is pretty much the way it's done.

The common way to fake a switch, and avoid using if and elif, if you wanted to, is to use a dict.

def time_machine(time_length, time_units):
    changes = {
        'years': datetime.timedelta(days=time_length*365),
        'days': datetime.timedelta(days=time_length),
        'hours': datetime.timedelta(hours=time_length),
        'minutes': datetime.timedelta(minutes=time_length),
    }
    return starter + changes[time_units]

I don't find this nearly as readable or intuitive, though.