如何使 python datetime.strptime 考虑到传递的时区?

Sri*_*i K 5 python datetime strptime python-2.7

尝试将字符串转换为datetime并将其保存到 db. 该字符串指定时区,但strptime不接受该%z选项。

datetime.strptime("Tue Feb 14 2017 15:30:01 GMT-0500", "%a %b %d %Y %H:%M:%S GMT%z")
Run Code Online (Sandbox Code Playgroud)

ValueError: 'z' 是格式为 '%a %b %d %Y %H:%M:%S GMT%z' 的错误指令

Spa*_*ine 5

%z自 Python 3.2 起受支持。

>>> from datetime import datetime
>>> datetime.strptime("Tue Feb 14 2017 15:30:01 GMT-0500", "%a %b %d %Y %H:%M:%S GMT%z")
datetime.datetime(2017, 2, 14, 15, 30, 1, tzinfo=datetime.timezone(datetime.timedelta(-1, 68400)))
Run Code Online (Sandbox Code Playgroud)

或者使用dateutil.parser,

>>> from dateutil import parser
>>> parser.parse('Tue Feb 14 2017 15:30:01 GMT-0500')
datetime.datetime(2017, 2, 14, 15, 30, 1, tzinfo=tzoffset(None, 18000))
Run Code Online (Sandbox Code Playgroud)