【问题标题】:Handle in Python date in format EEE MMM dd HH:mm:ss zzz yyyy以 EEE MMM dd HH:mm:ss zzz yyyy 格式处理 Python 日期
【发布时间】:2021-06-20 23:30:10
【问题描述】:

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

【问题讨论】:

  • 日期没有格式。它们是二进制值。格式仅适用于将日期文字(字符串)解析为实际日期,或将日期格式化为文本以进行显示或将其写入文件
  • 所以要么数据集包含错误的类型,字符串而不是日期,要么你试图修复一些没有被破坏的东西。如果数据集包含字符串,则需要修复加载它的代码并确保使用正确的类型。

标签: python string date


【解决方案1】:

首先安装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

【讨论】:

    猜你喜欢
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多