【问题标题】:How to convert a date string with both Etc/GMT into Python date time?如何将带有 Etc/GMT 的日期字符串转换为 Python 日期时间?
【发布时间】:2018-12-05 04:04:22
【问题描述】:

Apple 正在返回一种奇怪的收据到期日期格式:

2018-06-18 15:03:55 等/格林威治标准时间

from datetime import datetime
dt = datetime.strptime('2018-06-18 15:03:55 Etc/GMT', '%Y-%m-%d %H:%M:%S %Z')

Etc 和 GMT 都是一样的。

我曾尝试将它像这样转换为日期时间对象,但没有成功。

ValueError: time data '2018-06-18 15:03:55 Etc/GMT' does not match format '%Y-%m-%d %H:%M:%S %Z'

为什么首先要定义两个时区?以及如何让 Python 理解它?

【问题讨论】:

    标签: python python-3.6


    【解决方案1】:

    我不确定这是否是正确的方法..但它是否有帮助。

    import re
    from dateutil.parser import parse
    
    s = '2018-06-18 15:03:55 Etc/GMT'
    print( parse(re.sub("(?<=:\d{2}\s).*\/", r"", s)) )
    

    输出:

    2018-06-18 15:03:55+00:00
    
    • 我正在使用正则表达式从 src 日期时间中删除 Etc/
    • 使用dateutil 转换为日期时间对象。

    【讨论】:

    • 不,我需要它,否则没有时区日期是错误的。
    【解决方案2】:

    其实Etc/GMT appears to be a valid, existing time zone,只是datetime好像没有认出来。如果您有可能安装pytz,您可以执行以下操作:

    from datetime import datetime
    import pytz
    
    dt, tz = '2018-06-18 15:03:55 Etc/GMT'.rsplit(maxsplit=1) # rsplit() for simplicity, obviously re would make this safer
    
    dto = datetime.strptime(dt, '%Y-%m-%d %H:%M:%S').replace(tzinfo=pytz.timezone(tz))
    print(dto) # result: 2018-06-18 15:03:55+00:00
    

    【讨论】:

      猜你喜欢
      • 2020-12-15
      • 2011-10-07
      • 2014-02-23
      • 2015-03-24
      • 1970-01-01
      • 2020-06-03
      • 1970-01-01
      • 2012-06-04
      • 1970-01-01
      相关资源
      最近更新 更多