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 trialAizah Sadiq
2,435 Pointsstrftime and strptime
This is for challenge part 2. I cant seem to 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(datetime_object):
return datetime_object.strftime('%d %B %Y')
def from_string('September 29 2017'):
return datetime.strptime(from_string, "%B %d %Y")
5 Answers
Josh Keenan
20,315 PointsAlmost!
return datetime.datetime.strptime(my_date, my_format)
You need to take some date, and some format, and then convert that date to that format. Hope this helps, feel free to ask any other questions.
Josh Keenan
20,315 PointsYou have gone about the second one wrong. You want to be passing in two parameters to it, not just a raw string.
You will be receiving two things, a date, and a format for the date; you then need to put the date you have into that format. Remember that this isn't an instance method, meaning that you shouldn't be calling mydate.method()
of any kind. Hope this helps!
def from_string(my_date, my_format):
Josh Keenan
20,315 PointsNo, you need to use the parameters and not anything else, the last solution I posted works.
I'll explain it all.
def from_string(my_date, my_format):
return datetime.datetime.strptime(my_date, my_format)
The function has two parameters, the first is going to be a date, the second will be a format. You can't use a string like you did, because then you are setting it up to use just that format giving users no control. So when the function is called it would look like this:
from_string("09/24/12 18:30", "%m/%d/%y %H:%M")
The date and format could be different every time so we need to make sure we are ready for whatever the user throws at it.
Aizah Sadiq
2,435 Pointsso do you mean like this
def from_string(date, "%B %d %Y")
return strptime(from_string)
Is this correct?
Aizah Sadiq
2,435 PointsSo something like:
def from_string(date, strptime):
return datetime.datetime.strptime(date, "%B %d %Y")