Search code examples
pythondatetimeiso8601

how to convert a datetime string back to datetime object?


I am storing a datetime string in a database. Now I face a problem. When I fetch the string from the database, I need to convert it back to a datetime object...

Any easy way to do that?

The string of datetime looks like:

2010-11-13 10:33:54.227806

Solution

  • You want datetime.strptime(date_string, format).

    from datetime import datetime
    datetime.strptime("2010-11-13 10:33:54.227806", "%Y-%m-%d %H:%M:%S.%f")
    

    For details on the format string, see http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior