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

In python shell my timestrings.py script is working

why I`m getting Bummer!

timestrings.py
## Examples
# to_string(datetime_object) => "24 September 2012"
# from_string("09/24/12 18:30", "%m/%d/%y %H:%M") => datetime
import datetime
def to_string(date):
    day = datetime.datetime.strptime(date, '%d %B %Y')

    return day.strftime('%d %B %Y')

3 Answers

Steven Parker
Steven Parker
221,293 Points

I would expect this to always cause a TypeError.

The function*strptime* takes two string arguments, but you're providing with a datetime as the first argument.

You didn't say which task you were working on, perhaps you already passed task 1 and started working on task 2? But if so, you don't have two separate functions yet and you have some work to do with the arguments.

If you're still on task 1, you have too much code, and you should not need strptime at all.

Ryan S
Ryan S
27,276 Points

Hi Andrey,

The argument passed into the function is already a datetime object, not a string, so you don't need to use the .strptime() method. You only need to use .strftime() directly on the object.

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

Also, just a quick note that the word "date" is a reserved word in the datetime library. It is best to try to avoid using it as a variable name. It may not cause any problems in simple cases, but when working with dates and times you don't want to confuse a variable named "date" with the date object.

Good Luck.

Steven Parker
Steven Parker
221,293 Points

It may not be entirely accurate to refer to "date" as a reserved word.

A reserved word would normally only be something intrinsic to the language itself, such as def or class.

Steven and Ryan, Thanks for highlighting these points!!! Really good help! Thanks again

Ryan S
Ryan S
27,276 Points

Ah good point, Steven. My terminology is incorrect.