Alex Rivera | Logout

Error "can't subtract offset-naive and offset-aware datetimes"

Asked 2009-04-28T02:28:08.597
527

I have a time zone-aware timestamptz field in PostgreSQL. When I pull data from the table, I then want to subtract the time right now, so I can get its age.

The problem I'm having is that both datetime.datetime.now() and datetime.datetime.utcnow() seem to return time zone-unaware timestamps, which results in me getting this error:

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

Is there a way to avoid this (preferably without a third-party module being used)?


Thanks for the suggestions. However, trying to adjust the time zone seems to give me errors, so I'm just going to use time zone-unaware timestamps in PostgreSQL and always insert using:

NOW() AT TIME ZONE 'UTC'

That way, all my timestamps are UTC by default (even though it's more annoying to do this).

Edit
Report

1 Answer

6

The psycopg2 module has its own timezone definitions, so I ended up writing my own wrapper around utcnow:

def pg_utcnow():
    import psycopg2
    return datetime.utcnow().replace(
        tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None))

and just use pg_utcnow whenever you need the current time to compare against a PostgreSQL timestamptz

answered 2013-07-19T18:01:44.833

Your Answer