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

How do I make the string into "not a string", so that it can be used in the timedelta function?

?

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(int1, string1):
    if string1 == 'years':
        string2 = 'days'
        int2 = int1 * 365
        return starter + datetime.timedelta(string2 = int2)
    return starter + datetime.timedelta(string1 = int1)

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,457 Points

Hey Frederik Madsen, a great question. Many object types include methods to help convert a string into that type of object.

For a datetime object the method is called strptime. I think of this as “STRing Produce dateTIME” method. It takes the source string and a format template as arguments. The template is used to extract the data from the string. The data is then used as arguments to create a new datetime object.

The opposite is also true. There is another method to create a string from a datetime object called called strftime. I think of this as “STRing From dateTIME” method

Post back if you need more help. Good luck!!!