How to convert string to datetime in python [duplicate]
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.
精彩评论