Python - 如何从RSS提要中获取时区

时间:2014-01-01 10:45:45

标签: python datetime rss timezone feedparser

我需要获取RSS feed的已发布字段,我需要知道时区是什么。我以UTC格式存储日期,我希望另一个字段存储时区,以便稍后我可以操作日期时间。

我目前的代码如下:

for entry in feed['entries']:
    if hasattr(entry, 'published'):
        if isinstance(entry.published_parsed, struct_time):
            dt = datetime(*entry.published_parsed[:-3])

dt的最终值是UTC中的正确日期时间,但我还需要获取原始时区。有人可以帮忙吗?

编辑:

为了将来参考,即使它不是我原始问题的一部分,如果您需要操作非标准时区(如est),您需要根据您的规范制作转换表。感谢这个答案:Parsing date/time string with timezone abbreviated name in Python?

1 个答案:

答案 0 :(得分:4)

您可以使用parser.parse包的dateutil方法。

例如,对于statckoverflow:

import feedparser
from dateutil import parser, tz

url = 'http://stackoverflow.com/feeds/tag/python'
feed = feedparser.parse(url)
published = feed.entries[0].published
dt = parser.parse(published)

print(published)
print(dt) # that is timezone aware
print(dt.utcoffset()) # time zone of time
print(dt.astimezone(tz.tzutc())) # that is timezone aware as UTC

2012-11-28T19:07:32Z
2012-11-28 19:07:32+00:00
0:00:00
2012-11-28 19:07:32+00:00

您可以看到publishedZ结尾,表示时区为UTC:

在feedparser中查看History of Date Formats

Atom 1.0 states that all date elements “MUST conform to the date-time 
production in RFC 3339. 
In addition, an uppercase T character MUST be used to separate date and time, 
and an uppercase Z character MUST be present in the absence of 
a numeric time zone offset.”

另一个例子:

import feedparser
from dateutil import parser, tz

url = 'http://omidraha.com/rss/'
feed = feedparser.parse(url)
published = feed.entries[0].published
dt = parser.parse(published)

print(published)
print(dt) # that is timezone aware
print(dt.utcoffset()) # time zone of time
print(dt.astimezone(tz.tzutc())) # that is timezone aware as UTC

Thu, 26 Dec 2013 14:24:04 +0330
2013-12-26 14:24:04+03:30
3:30:00
2013-12-26 10:54:04+00:00

但这也取决于收到的时间数据格式和Feed类型。