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

datetime code

should be smth simple. how to assing datetime to some variable.

timestrings.py
import datetime
## 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):
    to_string = datetime.datetime(datetime)
    return to_string.strftime('d% B% Y%')

2 Answers

Ryan S
Ryan S
27,276 Points

Hi Asal,

There are a few things to clear up.

First, be careful about naming variables. You have a variable named to_string as well as a function named to_string. Because Python is a dynamically typed language, this can cause problems. Also, try not to use keywords such as 'datetime' as a variable name, since Python already has that word reserved in the datetime library. In the example they use 'datetime_object' as an argument, but it can be whatever you want as long as it's unique.

The second is that the function will take a datetime as an argument, so you don't need to try and convert it to a datetime since it already is one. All you need to do is convert it to a string.

The third is that your %'s are on the wrong side of the letters. They should come before the letters.

import datetime

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

Hope this helps,

Thanks Ryan. Of course it does help alot. I tried such code as well. But it must be the wrong parameter name that did not work. Thanks again. Will try to implement this new knowledge.