TypeError:无法比较原始偏移和知道偏移的日期时间 [英] TypeError: cant compare offset-naive and offset-aware datetimes
问题描述
我从电子邮件中获取datetime对象,然后尝试将其与datetime.now进行比较
I get datetime object from email message and then I try to compare it with datetime.now
然后我看到此错误
datetime.now()> datetime.strptime('Fri,31 Jan 2020 09:59:34 +0000(UTC)',%a,%d%b%Y%H:%M:%S%z(%Z)"
datetime.now() > datetime.strptime('Fri, 31 Jan 2020 09:59:34 +0000 (UTC)', "%a, %d %b %Y %H:%M:%S %z (%Z)"
TypeError:无法比较原始偏移日期和知道偏移的日期时间
TypeError: can't compare offset-naive and offset-aware datetimes
如何解决?
推荐答案
只要将偏移天真( datetime.now()
无时区信息)与可感知偏移的值进行比较,就会发生这种情况(UTC)时间.Python默认情况下对时区的支持不佳.即使您使用 datetime.utcnow()
从技术上进行比较,也只会返回您的UTC时间,但仍然具有幼稚的时区.
This will happen any time you compare an offset-naive (datetime.now()
No Timezone info) to an offset-aware (UTC) time. Python has poor timezone support by default. Even if you used datetime.utcnow()
to compare this technically just returns you the UTC time but still has a naive timezone.
我的建议是安装 pytz
软件包并执行以下操作:
My suggestion is to install the pytz
package and do:
import pytz
datetime.now().replace(tzinfo=pytz.UTC) > \
datetime.strptime('Fri, 31 Jan 2020 09:59:34 +0000 (UTC)',
"%a, %d %b %Y %H:%M:%S %z (%Z)")
有关更多参考,请参见: https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow
For further reference see: https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow
这篇关于TypeError:无法比较原始偏移和知道偏移的日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!