python - 将时区缩写解析为 UTC

标签 python datetime time timezone pytz

<分区>

如何将格式为 Feb 25 2010, 16:19:20 CET 的日期时间字符串转换为 unix 纪元?

目前我最好的方法是使用 time.strptime() 是这样的:

def to_unixepoch(s):
    # ignore the time zone in strptime
    a = s.split()
    b = time.strptime(" ".join(a[:-1]) + " UTC", "%b %d %Y, %H:%M:%S %Z")
    # this puts the time_tuple(UTC+TZ) to unixepoch(UTC+TZ+LOCALTIME)
    c = int(time.mktime(b))
    # UTC+TZ
    c -= time.timezone
    # UTC
    c -= {"CET": 3600, "CEST": 2 * 3600}[a[-1]]
    return c

我从其他问题中看到,可以使用 calendar.timegm()pytz 等来简化这个问题,但这些并不能处理缩写时区。

我想要一个需要最少多余库的解决方案,我喜欢尽可能多地使用标准库。

最佳答案

Python 标准库并没有真正实现时区。你应该使用 python-dateutil .它为标准 datetime 模块提供了有用的扩展,包括时区实现和解析器。

您可以使用 .astimezone(dateutil.tz.tzutc()) 将时区感知 datetime 对象转换为 UTC。对于作为时区感知日期时间对象的当前时间,您可以使用 datetime.datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc())

import dateutil.tz

cet = dateutil.tz.gettz('CET')

cesttime = datetime.datetime(2010, 4, 1, 12, 57, tzinfo=cet)
cesttime.isoformat()
'2010-04-01T12:57:00+02:00'

cettime = datetime.datetime(2010, 1, 1, 12, 57, tzinfo=cet)
cettime.isoformat() 
'2010-01-01T12:57:00+01:00'

# does not automatically parse the time zone portion
dateutil.parser.parse('Feb 25 2010, 16:19:20 CET')\
    .replace(tzinfo=dateutil.tz.gettz('CET'))

不幸的是,这种技术在重复的夏令时期间会出错。

关于python - 将时区缩写解析为 UTC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2335405/

相关文章:

python - 如何使 Python 脚本作为服务运行?

python - 与 IBM Watson Server 的连接中断

sql - 连接+时间差

ruby-on-rails - 给定一个 DateTime,如何获取特定时区中具有相同日期的时间范围?

mysql - 数据库模式,默认值为 NOW()

python - Django 类 View 未返回 HttpResponse 对象。它返回 None 而不是

python - 使用 `subprocess.Popen` 在 Python 中实时运行 Python 脚本

vb.net - DateTime.ParseExact - 失败

mysql - Speedwise,日期时间或时间戳哪个更好?

JavaScript 以已知间隔计算时间差