how to convert a string date into datetime format in python?

PythonDatetime

Python Problem Overview


How do I convert a a string of datetime into datetime format in python so that it can be compared with another date?

string_date = "2013-09-28 20:30:55.78200"
abc = datetime.datetime.now()

if abc  > string_date :
    print True

Python Solutions


Solution 1 - Python

The particular format for strptime:

datetime.datetime.strptime(string_date, "%Y-%m-%d %H:%M:%S.%f")
#>>> datetime.datetime(2013, 9, 28, 20, 30, 55, 782000)

Solution 2 - Python

You should use datetime.datetime.strptime:

import datetime

dt = datetime.datetime.strptime(string_date, fmt)

fmt will need to be the appropriate format for your string. You'll find the reference on how to build your format here.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPythonEnthusiastView Question on Stackoverflow
Solution 1 - PythonVeedracView Answer on Stackoverflow
Solution 2 - PythonThomas OrozcoView Answer on Stackoverflow