s = "June 19, 2010"
How do I conver that to a datetime object?
There's also the very good dateutil library, that can parse also stranger cases:
from dateutil.parsers import parse
d = parse(s)
Use datetime.strptime
. It takes the string to convert and a format code as arguments. The format code depends on the format of the string you want to convert, of course; details are in the documentation.
For the example in the question, you could do this:
from datetime import datetime
d = datetime.strptime(s, '%B %d, %Y')
As of python 2.5 you have the method datetime.strptime(): http://docs.python.org/library/datetime.html
dt = datetime.strptime("June 19, 2010", "%B %d, %Y")
if your locale is EN.
Use datetime.datetime.strptime:
>>> import datetime
>>> s = "June 19, 2010"
>>> datetime.datetime.strptime(s,"%B %d, %Y")
datetime.datetime(2010, 6, 19, 0, 0)
精彩评论