解析时区缩略语UTC [英] Parse timezone abbreviation to UTC

查看:150
本文介绍了解析时区缩略语UTC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将窗体 2010年2月25日,16:19:20 CET 的日期时间字符串转换为unix纪元?

How can I convert a date time string of the form Feb 25 2010, 16:19:20 CET to the unix epoch?

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

Currently my best approach is to use time.strptime() is this:

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 等等,以简化这个,但这些不处理缩写的时区。

I see from other questions that it might be possible to use calendar.timegm(), and pytz among others to simplify this, but these don't handle the abbreviated time zones.

我想要一个需要最少的图书馆的解决方案,我喜欢保持标准库与p ossible。

I'd like a solution that requires minimal excess libraries, I like to keep to the standard library as much as possible.

推荐答案

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

The Python standard library does not really implement time zones. You should use python-dateutil. It provides useful extensions to the standard datetime module including a time zones implementation and a parser.

您可以转换时间区域意识 datetime 对象到UTC与 .astimezone(dateutil.tz.tzutc())。对于当前时间作为时区感知的datetime对象,可以使用 datetime.datetime.utcnow()。replace(tzinfo = dateutil.tz.tzutc())。 p>

You can convert time zone aware datetime objects to UTC with .astimezone(dateutil.tz.tzutc()). For the current time as a timezone aware datetime object, you can use 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'))

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

Unfortunately this technique will be wrong during the repeated daylight savings time hour.

这篇关于解析时区缩略语UTC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆