I have a date string in following format 2011-03-07 how to convert this to datetime in python?
Asked
Active
Viewed 4.2k times
7
-
1`I had the similar question` http://stackoverflow.com/questions/3700118/getting-formatted-datetime-in-python-like-in-php – sultan Mar 07 '11 at 13:01
-
1A Google search with the query `python convert datetime to string` returned 106.000 results! – ssoler Mar 07 '11 at 16:51
5 Answers
22
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 ;)

Sun Liwen
- 1,224
- 1
- 15
- 21

Mark Longair
- 446,582
- 72
- 411
- 327
5
You can use datetime.date
:
>>> import datetime
>>> s = '2011-03-07'
>>> datetime.date(*map(int, s.split('-')))
datetime.date(2011, 3, 7)

rubik
- 8,814
- 9
- 58
- 88
3
Try this:
import datetime
print(datetime.datetime.strptime('2011-03-07', '%Y-%m-%d'))

Michał Niklas
- 53,067
- 18
- 70
- 114
3
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.

mavnn
- 9,101
- 4
- 34
- 52
1
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.

vonPetrushev
- 5,457
- 6
- 39
- 51