具有正确的时区正确的日期时间 [英] Have a correct datetime with correct timezone

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

问题描述

我正在使用 feedparser 来获取RSS数据。
这是我的代码:

I am using feedparser in order to get RSS data. Here is my code :

>>> import datetime
>>> import time
>>> import feedparser

>>> d=feedparser.parse("http://.../rss.xml")

>>> datetimee_rss = d.entries[0].published_parsed

>>> datetimee_rss
time.struct_time(tm_year=2015, tm_mon=5, tm_mday=8, tm_hour=16, tm_min=57, tm_sec=39, tm_wday=4, tm_yday=128, tm_isdst=0)

>>> datetime.datetime.fromtimestamp(time.mktime(datetimee_rss))
datetime.datetime(2015, 5, 8, 17, 57, 39)

在我的时区(FR)中,实际日期为 2015年5月8日18:57

In my timezone (FR), the actual date is May, 8th, 2015 18:57.

在RSS XML中,值为< pubDate> Fri,08 May 2015 18:57:39 + 0200< / pubDate>

In the RSS XML, the value is <pubDate>Fri, 08 May 2015 18:57:39 +0200</pubDate>

当我将其解析成日期时间时,我得到了 2015,5,8,17,57,39

When I parse it into datetime, I got 2015, 5, 8, 17, 57, 39.

如何使 2015,5,8,18,57,39 没有肮脏的黑客,正确的时区?

How to have 2015, 5, 8, 18, 57, 39 without dirty hack, but simply by configuring the correct timezone ?

编辑:

通过做:

>>> from pytz import timezone

>>> datetime.datetime.fromtimestamp(time.mktime(datetimee_rss),tz=timezone('Euro
pe/Paris'))
datetime.datetime(2015, 5, 8, 17, 57, 39, tzinfo=<DstTzInfo 'Europe/Paris' CEST+2:00:00 DST>)

更好的是,在脚本的其余部分看起来似乎不起作用,我有很多 TypeError:无法比较offset-naive和offset-aware datetimes 错误

I got something nicer, however, it doesn't seem to work in the rest of the script, I got plenty of TypeError: can't compare offset-naive and offset-aware datetimes error.

推荐答案

feedparser 提供原始的datetime字符串您可以从属性名称的 _parsed 后缀),因此,如果您知道字符串的格式,您可以自己将其解析成tz-aware datetime对象。

feedparser does provide the original datetime string (just remove the _parsed suffix from the attribute name), so if you know the format of the string, you can parse it into a tz-aware datetime object yourself.

例如,使用您的代码,您可以获取tz感知对象:

For example, with your code, you can get the tz-aware object as such:

datetime.datetime.strptime(d.entries[0].published, '%a, %d %b %Y %H:%M:%S %z')

有关 strptime()的更多参考,请参阅 https://docs.python.org/2/library/datetime.html# strftime-and-strptime-behavior

for more reference on strptime(), see https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

编辑:由于Python 2.x不支持%z 指令,使用 python-dateutil 代替

Since Python 2.x doesn't support %z directive, use python-dateutil instead

pip install python-dateutil

然后

from dateutil import parser
datetime_rss = parser.parse(d.entries[0].published)

文档在 https://dateutil.readthedocs.org/en/latest/

这篇关于具有正确的时区正确的日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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