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
Praful Bagai
  • 16,684
  • 50
  • 136
  • 267

2 Answers2

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)
Veedrac
  • 58,273
  • 15
  • 112
  • 169
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.

Thomas Orozco
  • 53,284
  • 11
  • 113
  • 116