开发者

Lets say I have a string...how do I convert that to a datetime? [duplicate]

开发者 https://www.devze.com 2023-01-04 19:09 出处:网络
This question already has answers here: Convert string "Jun 1 2005 1:33PM" into datetime (26 answers)
This question already has answers here: Convert string "Jun 1 2005 1:33PM" into datetime (26 answers) 开发者_C百科 Closed 8 years ago.
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)
0

精彩评论

暂无评论...
验证码 换一张
取 消