简体   繁体   English

即使使用Dateutil解析器,Python 2.7 Datetime对象的偏移也无法察觉

[英]Python 2.7 Datetime Object Offset Unaware Even With Dateutil Parser

18 tz = pytz.timezone('America/Chicago')
19 TZOFFSETS = {'CST' : -21600}
20 POSTS_SINCE_HOUR = 1 
21 now_date = datetime.datetime.now(tz)
22 time_stamp = now_date - datetime.timedelta(hours=POSTS_SINCE_HOUR)
23 
24 thread_batch = []
25 for thread in threads:
26     last_post_time =  parse(
27             thread["LatestPostDate"],
28             tzinfos=TZOFFSETS)
29             
30     if last_post_time > time_stamp:
31         thread_batch.append(thread)


one@chat-dash ~/.willie $ python req.py 
Traceback (most recent call last):
  File "req.py", line 30, in <module>
    if last_post_time > time_stamp:
TypeError: can't compare offset-naive and offset-aware datetimes

I don't understand why it is complaining about this. 我不明白为什么它对此有所抱怨。 I used datutil.parser parse to make last_post_time offset-aware. 我使用datutil.parser parse来使last_post_time偏移量意识。

The tzinfos parameter to parse does not specify which timezone to use, it merely allows you to add new custom time zones to the ones that dateutil recognizes. parsetzinfos参数未指定要使用的时区,它仅允许您向dateutil识别的时区添加新的自定义时区。 To get a timezone in the resulting datetime, the string passed to parse must include a timezone string. 要在结果日期时间中获取时区,传递给parse的字符串必须包含时区字符串。

If your string doesn't include a time zone, you need to add the timezone yourself after the datetime is returned. 如果您的字符串不包含时区,则需要在返回日期时间后自行添加时区。

更新:我最终无视parse(),使用datetime strptime,然后使用localize()添加时区。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM