如何在 Python 中解析具有 UTC 偏移量的时区?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1302161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I parse timezones with UTC offsets in Python?
提问by mike
Let's say I have a timezone like "2009-08-18 13:52:54-04". I can parse most of it using a line like this:
假设我有一个像“2009-08-18 13:52:54-04”这样的时区。我可以使用这样的一行来解析其中的大部分内容:
datetime.strptime(time_string, "%Y-%m-%d %H:%M:%S")
However, I can't get the timezone to work. There's a %Z that handles textual timezones ("EST", "UTC", etc) but I don't see anything that can parse "-04".
但是,我无法让时区工作。有一个 %Z 处理文本时区(“EST”、“UTC”等),但我看不到任何可以解析“-04”的东西。
采纳答案by Dawie Strauss
I ran across the same issue recently and worked around it using this code:
我最近遇到了同样的问题并使用以下代码解决了它:
gmt_offset_str = time_string[-3:]
gmt_offset_seconds = int(gmt_offset_str)*60*60
timestamp = time.strptime(time_string[:-4], '%Y-%m-%d %H:%M:%S')
return time.localtime(time.mktime(timestamp)-gmt_offset_seconds)
I would also be interested in a more elegant solution.
我也会对更优雅的解决方案感兴趣。
回答by conny
Maybe you could use dateutil.parser.parse? That method is also mentioned on wiki.python.org/WorkingWithTime.
也许你可以使用dateutil.parser.parse?wiki.python.org/WorkingWithTime上也提到了该方法。
>>> from dateutil.parser import parse
>>> parse("2009-08-18 13:52:54-04")
datetime.datetime(2009, 8, 18, 13, 52, 54, tzinfo=tzoffset(None, -14400))
(is this question a duplicate?)
(这个问题是重复的吗?)
回答by iElectric
use Babel, specifically parse_datetime.
使用Babel,特别是parse_datetime。
回答by Esteban Küber
You can do that directrly on the constructor: class datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[,
tzinfo]]]]])
, tzinfo being a datetime.tzinfo
dervided object.
您可以直接在构造函数上执行此操作:class datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[,
tzinfo]]]]])
, tzinfo 是一个datetime.tzinfo
派生对象。
tzinfois an abstract base clase, meaning that this class should not be instantiated directly. You need to derive a concrete subclass, and (at least) supply implementations of the standard tzinfo methods needed by the datetime methods you use. The datetime module does not supply any concrete subclasses of tzinfo.
tzinfo是一个抽象基类,这意味着不应直接实例化此类。您需要派生一个具体的子类,并且(至少)提供您使用的日期时间方法所需的标准 tzinfo 方法的实现。datetime 模块不提供 tzinfo 的任何具体子类。
What you need to override is the utcoffset(self, dt)
method.
您需要覆盖的是utcoffset(self, dt)
方法。
Return offset of local time from UTC, in minutes east of UTC. If local time is west of UTC, this should be negative. Note that this is intended to be the total offset from UTC; for example, if a tzinfo object represents both time zone and DST adjustments, utcoffset() should return their sum. If the UTC offset isn't known, return None. Else the value returned must be a timedelta object specifying a whole number of minutes in the range -1439 to 1439 inclusive (1440 = 24*60; the magnitude of the offset must be less than one day). Most implementations of utcoffset() will probably look like one of these two:
return CONSTANT # fixed-offset class
return CONSTANT + self.dst(dt) # daylight-aware class
If utcoffset() does not return None, dst() should not return None either.
返回本地时间与 UTC 的偏移量,以 UTC 以东的分钟数为单位。如果当地时间在 UTC 以西,这应该是负数。请注意,这是与 UTC 的总偏移量;例如,如果 tzinfo 对象同时表示时区和 DST 调整,则 utcoffset() 应返回它们的总和。如果 UTC 偏移量未知,则返回 None。否则返回的值必须是一个 timedelta 对象,它指定了 -1439 到 1439 范围内的整数分钟数(1440 = 24*60;偏移量必须小于一天)。utcoffset() 的大多数实现可能看起来像这两个之一:
return CONSTANT # fixed-offset class
return CONSTANT + self.dst(dt) # daylight-aware class
如果 utcoffset() 不返回 None , dst() 也不应该返回 None 。
The default implementation of utcoffset() raises NotImplementedError.
utcoffset() 的默认实现会引发 NotImplementedError。