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

Andrei Oprescu
Andrei Oprescu
9,547 Points

I don't know how to format this.

I have a question that asks:

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

And I have a code:

import datetime

def to_string(datetime_object): time = datetime.datetime_object.strftime('%d %b %Y') return time

Can you tell me what I did wrong?

thanks!

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(datetime_object):
    time = datetime.datetime_object.strftime('%d %b %Y')
    return time

1 Answer

Ben Reynolds
Ben Reynolds
35,170 Points
  1. You don't need "datetime." at the beginning of the variable assignment.
  2. The symbol for the full month name should be capital B instead of lowercase.
  3. (optional) This one's not a huge deal but you could also shorten the code a bit and just return the result of the strftime method call on one line instead of assigning it to a new variable first (time). In other words the return statement could be the only line in the to_string method.