首先安装dateutil 到python -m pip install python-dateutil。
然后使用下一个代码:
Try it online!
import datetime, dateutil.parser
s = 'Mon May 18 20:25:32 GMT+02:00 2020'
t = datetime.datetime.strptime(s, '%a %b %d %H:%M:%S %Z%z %Y') # 'EEE MMM dd HH:mm:ss zzz yyyy'
print(t.astimezone(dateutil.tz.tzutc())) # UTC TimeZone
print(t.astimezone(dateutil.tz.tzlocal())) # Local TimeZone
输出:
2020-05-18 18:25:32+00:00
2020-05-18 21:25:32+03:00
还有一种简单的方法是使用 dateutil 的解析器来自动猜测格式,但它有时可能无法正常工作:
Try it online!
import dateutil.parser
s = 'Mon May 18 20:25:32 GMT+02:00 2020'
t = dateutil.parser.parse(s)
print(t.astimezone(dateutil.tz.tzutc())) # UTC TimeZone
print(t.astimezone(dateutil.tz.tzlocal())) # Local TimeZone
输出(猜错时区):
2020-05-18 22:25:32+00:00
2020-05-19 01:25:32+03:00
让 dateutil 的猜测器正常工作的一种方法是删除 ' GMT' 子字符串,如果您在任何地方都有相同的时区名称子字符串。代码如下:
import dateutil.parser
s = 'Mon May 18 20:25:32 GMT+02:00 2020'.replace(' GMT', '')
t = dateutil.parser.parse(s)
print(t.astimezone(dateutil.tz.tzutc())) # UTC TimeZone
print(t.astimezone(dateutil.tz.tzlocal())) # Local TimeZone
输出:
2020-05-18 18:25:32+00:00
2020-05-18 21:25:32+03:00