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 trialJohn Mercer
31,479 PointsWhy does my "from_string" time conversion method not work in Treehouse?
I have written a Python function, "from_string," which takes two parameters, a date formatted as a string, and a valid format conversion string. I have tested this code under Python 3.4 on my computer, and it works well, but Treehouse rejects it. Why is Treehouse rejected code that works on my computer? Am I missing something here?
## Examples
# to_string(datetime_object) => "24 September 2012"
# from_string("09/24/12 18:30", "%m/%d/%y %H:%M") => datetime
import datetime
from datetime import datetime
def to_string(dt):
return dt.strftime("%d %B %Y")
def from_string(d, f):
return datetime.strptime(d, f)
4 Answers
Mikael Enarsson
7,056 PointsIt works if you remove from datetime import datetime
and use datetime.datetime.strptime()
instead. I don't know why, maybe some kind of conflict?
Kenneth Love
Treehouse Guest TeacherYep, that was failing for a really stupid reason. Your code should pass in its original form now.
I will point out, though, that it's a bit weird to import datetime
and then from datetime import datetime
, effectively overwriting the first import.
John Mercer
31,479 PointsThank you. You are absolutely correct. Still, I find it strange that Treehouse's Python interpreter could not allow for alternate solutions that work, such as my original code.
Again, many thanks for your help.
Mikael Enarsson
7,056 PointsNo problem, and I agree. Usually if it's a workable solution and they see it they add it, so let's hope that it's the case this time ^^
james white
78,399 PointsKenneth said:
"I will point out, though, that it's a bit weird to import datetime.."
So then you don't use this (??):
import datetime
I tried just this code by itself (without any import):
def to_string(dt):
return dt.strftime("%d %B %Y")
def from_string(d, f):
return datetime.datetime.strptime(d, f)
..but it gave me an error and I ended up having to use
import datatime
no matter how 'weird', to get it to pass.
Brittany Kozura
17,143 PointsNo, he was talking about line 2 in the original code, which said "import datetime from datetime" which is repeating the first line and is useless. You MUST import datetime.