开发者

How to convert string to datetime in python [duplicate]

This question already has answers here: Convert string "Jun 1 2005 1:33PM" into datetime (26 answers) 开发者_如何学C Closed 5 years ago.

I have a date string in following format 2011-03-07 how to convert this to datetime in python?


Try the following code, which uses strptime from the datetime module:

from datetime import datetime
datetime.strptime('2011-03-07','%Y-%m-%d')

I note that this (and many other solutions) are trivially easy to find with Google ;)


You can use datetime.date:

>>> import datetime
>>> s = '2011-03-07'
>>> datetime.date(*map(int, s.split('-')))
datetime.date(2011, 3, 7)


The datetime.datetime object from the standard library has the datetime.strptime(date_string, format) constructor that is likely to be more reliable than any manual string manipulation you do yourself.

Read up on strptime strings to work out how to specify the format you want.


Try this:

import datetime
print(datetime.datetime.strptime('2011-03-07', '%Y-%m-%d'))


Check out datetime.datetime.strptime and its sister strftime for this:

from datetime import datetime
time_obj = datetime.strptime("2011-03-07", "%Y-%m-%d")

It is used for parsing and formating from datetime to string and back.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜