代码之家  ›  专栏  ›  技术社区  ›  Matt Joiner

将时区缩写解析为UTC[重复]

  •  4
  • Matt Joiner  · 技术社区  · 15 年前

    如何转换窗体的日期时间字符串 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 回复  |  直到 15 年前
        1
  •  7
  •   joeforker    15 年前

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

    您可以转换时区感知 日期时间 对象到UTC .astimezone(dateutil.tz.tzutc()) 。对于当前时间作为时区感知的日期时间对象,可以使用 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'))
    

    不幸的是,这种方法在重复的夏令时中会出错。