如何使 python datetime.strptime 考虑到已通过的时区?

How to make python datetime.strptime take into account timezone passed?

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

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

ValueError: 'z' is a bad directive in format '%a %b %d %Y %H:%M:%S GMT%z'

%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)))

或使用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))