I have a date string in following format 2011-03-07 how to convert this to datetime in python?
5 Answers
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 ;)
Comments
You can use datetime.date:
>>> import datetime
>>> s = '2011-03-07'
>>> datetime.date(*map(int, s.split('-')))
datetime.date(2011, 3, 7)
Comments
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.
I had the similar questionstackoverflow.com/questions/3700118/…python convert datetime to stringreturned 106.000 results!