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 trialMichael Steinman
11,012 PointsConvert two strings to a datetime
Here's the task:
Create a new function named from_string that takes two arguments: a date as a string and an strftime-compatible format string, and returns a datetime created from them.
My problem is that I don't think I understand what the question is asking. If I'm supposed to take two strings as inputs and then convert them to a datetime, wouldn't I need to know the format of the strings to use strptime? How can I write this function without knowing the format?
1 Answer
Andreas cormack
Python Web Development Techdegree Graduate 33,011 PointsHi Michael
The task asks you to create a function that takes two arguments, one a datetime string and one a strftime pattern string. The idea being you use the passed in arguments to return a datetime object. You can use the strptime method of the datetime class takes two arguments a string reprezentation of a datime and a format.
see below
import datetime
def from_string(datestring,dateformat):
return datetime.datetime.strptime(datestring, dateformat)