views:

1124

answers:

2

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).

Hopefully I can eventually find a fix for this.

+2  A: 

have you tried to remove the timezone awareness?

from http://pytz.sourceforge.net/

naive = dt.replace(tzinfo=None)

may have to add time zone conversion as well.

phillc
This seems to be the only way to do it. Seems pretty lame that python's got such crappy support for timezones that it needs a third-party module to work with timestamps properly..
Ian
python 3000 should be fine.
phillc
+1  A: 

Is there some pressing reason why you can't handle the age calculation in PostgreSQL itself? Something like

select *, age(timeStampField) as timeStampAge from myTable
Nic Gibson
Yes there is.. but I was mostly asking because I want to avoid doing all the calculations in postgre.
Ian