【问题标题】:Python - How to get timezone from RSS feedPython - 如何从 RSS 提要中获取时区
【发布时间】:2014-01-01 10:45:44
【问题描述】:

我需要获取 RSS 提要的已发布字段,并且我需要知道时区是什么。我将日期存储在 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?

【问题讨论】:

  • 在您的编辑中:使用 pytz 在 Python 中操作时区。

标签: python datetime rss timezone feedparser


【解决方案1】:

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

以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

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

【讨论】:

  • 谢谢,它对我有用。我遇到了日期格式不正确的提要问题:2014 年 1 月 1 日星期三 05:33:02 EST。你知道怎么解决吗?
猜你喜欢
  • 2016-11-21
  • 2012-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
  • 1970-01-01
  • 2014-07-29
相关资源
最近更新 更多