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).
To fix TypeError: can't compare offset-naive and offset-aware datetimes with Python, we can use the utc. localize method to convert both times to aware datetimes. to call utc. localize to convert datetime_start and datetime_end to time zone aware datetimes.
To remove timestamp, tzinfo has to be set None when calling replace() function. First, create a DateTime object with current time using datetime. now(). The DateTime object was then modified to contain the timezone information as well using the timezone.
Timezone aware object using datetime now(). time() function of datetime module. Then we will replace the value of the timezone in the tzinfo class of the object using the replace() function. After that convert the date value into ISO 8601 format using the isoformat() method.
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.
edit: Please be aware the age of this answer. An answer involving ADDing the timezone info instead of removing it in python 3 is below. https://stackoverflow.com/a/25662061/93380
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With