Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Dates and Times in Python Dates and Times strftime & strptime

Still lost on date.times

Hey there, Floundering in this date.time video series. Needing some help. My plan is to go back and thoroughly review this series and make it stick. Right now, just sorta lost....

## Examples
# to_string(datetime_object) => "24 September 2012"
# from_string("09/24/12 18:30", "%m/%d/%y %H:%M") => datetime
def to_string(datetime.datetime):

3 Answers

Chris Freeman
Chris Freeman
Treehouse Moderator 67,893 Points

Hey matthew mahoney, there are two aspects to dealing with datetime object. Basically converting data into (strptime) and out of (strftime) a datetime object; and manipulating datetime objects and the related timedelta objects.

For functions that manipulate a datetime object, the function parameter can be a regular variable name, say, date1, etc.

Adatetime object can be used in math equations. When added or subtracted, two datetime objects yield a new timedelta object. Math between a datetime object and a timedelta Yields a new datetime object.

So the form of your solutions would be:

def my_func(string, format):
    # call to strptime
    # return results

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

Okay, so I liked your ab joke... lol

I sorted the last challenge but this one still has me stumped.

"Create a function named to_string that takes a datetime and gives back a string in the format "24 September 2012"."

import datetime

def to_string(date1):
    return date1.datetime.strptime('%d %B %Y')
Chris Freeman
Chris Freeman
Treehouse Moderator 67,893 Points

You’re very close. “To string” needs to use strftime since it’s a str-Formatted-time.

The object date1 is a datetime object so it has the method strftime. :point_right: remove the .datetime

Okay, Chris Freeman finally got that one! Now to the second half Strptime... any clues for this one?

import datetime

def to_string(date1):
    return date1.strftime('%d %B %Y')

def from_string(string_date, a_strftime):

okay, supposed to be strftime but... still doesn't work