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

Code executes in console but is not passing in Code Challenge

If i do it step by step in console without creating a function it works but wont work in Code Challenge, Please Help!! Error Says " Bummer! to_string returned the wrong string. Returned '24 September 2012'." Arent I supposed to return '24 September 2012'??? it not making sense to me

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(datetime1):
  strr =  "%d %B %Y"
  date = datetime.datetime.now()
  datetime1 = date.replace(year = 2012, month = 9, day = 24)
  datetime2 = datetime1.strftime(strr)
  return datetime2

3 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 Points

The issue with your code is that it returns 24 September 2015 every time. due to the date.replace() you've used. The idea is to proved a function that converts any date passed in to the proper format. Reworking your code, you can solve it:

## Examples
# to_string(datetime_object) => "24 September 2012"
# from_string("09/24/12 18:30", "%m/%d/%y %H:%M") => datetime
def to_string(datetime1):
  strr =  "%d %B %Y"
  #date = datetime.datetime.now()  #<-- not needed
  #datetime1 = date.replace(year = 2012, month = 9, day = 24)  #<-- not needed
  datetime2 = datetime1.strftime(strr) 
  return datetime2

The last two statements could be combined into one.

The question is asking that you take a datetime object and print it out using strftime with the so that the datetime is printed in the format (number of the day) (month written out) (full year). Thus you do not need datetime.datetime.now() or the date.replace, or even strr (because you can do a direct substitute of '%d %B %Y' for strr in the function. And voila! six lines of code are now three.

thanks gentlemen, i appreciate the help it worked. both of you are correct... thanx again