Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo ObjectID: "can't compare offset-naive and offset-aware datetimes" even with pytz

I'm trying to prettify ObjectIDs timestamp with py-pretty but it keeps giving me a TypeError:

TypeError: can't compare offset-naive and offset-aware datetimes

even after I attempt convert the timestamp to a timezone unaware UTC date with Pytz. This is the code I'm trying

import datetime
import pytz
import pretty
# ...

song = db.songs.find_one( { 'GUID' : 0123 } )
dateTimeUnaware = song['_id'].generation_time.now(pytz.utc)
prettyDate = pretty.date( dateTimeUnaware )

Why does this keep giving me the type error? Shouldn't the pytz function make it timezone agnostic?

like image 922
zakdances Avatar asked Oct 19 '12 06:10

zakdances


1 Answers

I'm not a py-pretty expert, but your code doesn't convert timezone-aware date to timezone unaware date.

It just takes the current date (using now) in the utc timezone (so timezone aware).

You can naively convert tz-aware datetime to tz-unaware one by using:

your_datetime_var.replace(tzinfo=None)

in your case:

song['_id'].generation_time.replace(tzinfo=None)

Note that "naively" in this case means that all fields related to date and time will have the same value as the original one, but the information about timezone and DST will be lost.

BTW it looks like py-pretty is unmaintained (last upload to pypi in 2010, source code inaccessible) so it might be a good idea to look for replacement

like image 92
soulcheck Avatar answered Sep 22 '22 18:09

soulcheck