以 EEE MMM dd HH:mm:ss zzz yyyy 格式处理 Python 日期

时间:2021-03-24 09:14:57

标签: python string date

在数据集中,我有一些格式为 EEE MMM dd HH:mm:ss zzz yyyy 的日期时间,例如“Mon May 18 20:25:32 GMT+02:00 2020”。 如何在 Python 中以 ISO 格式和机器本地时间转换此字符串?

1 个答案:

答案 0 :(得分:0)

首先通过 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