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 trialPedro Leão
2,645 Pointsto_string function using date.strftime and date.strptime not returning the right string
The challenge says that you should create a 'to_string' function that returns '24 September 2012'. And I created a function that gives the error: to_string
returned the wrong string. Returned '24 September 2012'.
The code I used was the following:
import datetime
def to_string(datetime_object): t = datetime_object.strptime("09/24/12", "%m/%d/%y") return t.strftime("%d %B %Y")
Can anyone help me with this? Did anyone solved this already that could post here their code? Thanks
## 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):
string = datetime_object.strptime("09/24/12", "%m/%d/%y")
return string.strftime("%d %B %Y")
2 Answers
Chris Freeman
Treehouse Moderator 68,441 PointsYou're doing more work than necessary. `datetime.strftime directly:
## 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_object):
string = datetime_object.strftime("%d %B %Y")
return string
Jonathan Endersby
9,807 PointsChris Freeman could you remove the string and just have it as 'return datetime_object.strfttime("%d %B %Y")' ?
Chris Freeman
Treehouse Moderator 68,441 PointsYes. That works just as well.
Pedro Leão
2,645 PointsPedro Leão
2,645 PointsGreat! It worked. Thanks a lot. This will probably be helpful for further challenges. Really appreciated