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) 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....

timestrings.py
## 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
MOD
Chris Freeman
Treehouse Moderator 68,423 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 68,423 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