103

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
0

2 Answers 2

183

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)
Sign up to request clarification or add additional context in comments.

2 Comments

What platforms is %f supported on?
@JonathanLeaders I suggest you ask a separate question about that.
30

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.

5 Comments

You mean to say dt = datetime.datetime.strptime(string_date, "YYYY-MM-DD %H:%M%:%S") ?
@user1162512 That format will not be correct, check my updated answer.
not working with dt = datetime.datetime.strptime(string_date, "YYYY-MM-DD %H:%M%:%S") . Says format is not valid
It's not valid @user1162512, as you were told. For a start your string has fractional seconds, which you haven't accounted for in your format. If you read the documentation it'll help.
Thanks. It worked with the answer provided by @Veedrac

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.