如何将日期时间字符串转换回datetime对象?

Bin*_*hen 11 python datetime

datetime在数据库中存储一个字符串.现在我遇到了一个问题.当我从数据库中获取字符串时,我需要将其转换回datetime对象...

有什么简单的方法吗?

日期时间字符串如下所示:

2010-11-13 10:33:54.227806
Run Code Online (Sandbox Code Playgroud)

Nic*_*ght 23

你想要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")
Run Code Online (Sandbox Code Playgroud)

有关格式字符串的详细信息,请参阅http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior


die*_*us9 5

我建议你安装python-dateutilt:

from dateutil import parser
d = parser.parse(yourstring)
Run Code Online (Sandbox Code Playgroud)

该库以"智能"方式从日期字符串中获取日期时间对象...