12

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

3
  • 1
    I had the similar question stackoverflow.com/questions/3700118/… Commented Mar 7, 2011 at 13:01
  • 1
    A Google search with the query python convert datetime to string returned 106.000 results! Commented Mar 7, 2011 at 16:51
  • 1
    @ssoler and this was the top result Commented May 14, 2024 at 13:35

5 Answers 5

29

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 ;)

Sign up to request clarification or add additional context in comments.

Comments

5

You can use datetime.date:

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

Comments

5

Try this:

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

Comments

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.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.