解析时区缩写为UTC

4 投票
1 回答
8525 浏览
提问于 2025-04-15 19:43

我想知道怎么把一个日期时间字符串,比如 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 等工具来简化这个过程,但这些方法对缩写的时区处理得不好。

我希望能找到一个解决方案,尽量少用额外的库,我想尽量使用标准库。

1 个回答

7

Python的标准库其实并没有真正实现时区的功能。如果你需要处理时区,建议使用python-dateutil这个库。它为标准的datetime模块提供了一些很有用的扩展,包括时区的实现和解析器。

你可以用.astimezone(dateutil.tz.tzutc())把带有时区信息的datetime对象转换成UTC时间。如果你想获取当前时间的带时区的datetime对象,可以使用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'))

不过要注意,这种方法在夏令时重复的那一小时会出错。

撰写回答