I have a timezone 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 it's age.
The problem I'm having is that both datetime.datetime.now()
and datetime.datetime.utcnow()
seem to return timezone 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).
EDIT: Thanks for the suggestions, however trying to adjust the timezone seems to give me errors.. so I'm just going to use timezone unaware timestamps in PG 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).
I know some people use Django specifically as an interface to abstract this type of database interaction. Django provides utilities that can be used for this:
You do need to set up a basic Django settings infrastructure, even if you are just using this type of interface (in settings, you need to include
USE_TZ=True
to get an aware datetime).By itself, this is probably nowhere near enough to motivate you to use Django as an interface, but there are many other perks. On the other hand, if you stumbled here because you were mangling your Django app (as I did), then perhaps this helps...
The psycopg2 module has its own timezone definitions, so I ended up writing my own wrapper around utcnow:
and just use
pg_utcnow
whenever you need the current time to compare against a PostgreSQLtimestamptz
Is there some pressing reason why you can't handle the age calculation in PostgreSQL itself? Something like
The correct solution is to add the timezone info e.g., to get the current time as an aware datetime object in Python 3:
On older Python versions, you could define the
utc
tzinfo object yourself (example from datetime docs):then:
I've found
timezone.make_aware(datetime.datetime.now())
is helpful in django (I'm on 1.9.1). Unfortunately you can't simply make adatetime
object offset-aware, thentimetz()
it. You have to make adatetime
and make comparisons based on that.have you tried to remove the timezone awareness?
from http://pytz.sourceforge.net/
may have to add time zone conversion as well.
edit: Please be aware the age of this answer. A Python 3 answer is below.