dman
dman

Reputation: 11064

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.

Upvotes: 0

Views: 169

Answers (2)

dman
dman

Reputation: 11064

Update: I ended up disregarding the parse(), used datetime strptime, and then used localize() to add a timezone.

Upvotes: 0

Mark Ransom
Mark Ransom

Reputation: 308120

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. To get a timezone in the resulting datetime, the string passed to parse must include a timezone string.

If your string doesn't include a time zone, you need to add the timezone yourself after the datetime is returned.

Upvotes: 1

Related Questions