如何在 python 中将字符串日期转换为日期时间格式?

如何在 python 中将一个 datetime 字符串转换为 datetime 格式,以便与另一个日期进行比较?

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


if abc  > string_date :
print True
259054 次浏览

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.

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)