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).
This is a very simple and clear solution
Two lines of code
You must mange your datetime variables with the same time info
I came up with an ultra-simple solution:
It works with both timezone-aware and timezone-naive datetime values. And no additional libraries or database workarounds are required.
I know this is old, but just thought I would add my solution just in case someone finds it useful.
I wanted to compare the local naive datetime with an aware datetime from a timeserver. I basically created a new naive datetime object using the aware datetime object. It's a bit of a hack and doesn't look very pretty but gets the job done.
...here comes the fudge...
I also faced the same problem. Then I found a solution after a lot of searching .
The problem was that when we get the datetime object from model or form it is offset aware and if we get the time by system it is offset naive.
So what I did is I got the current time using timezone.now() and import the timezone by from django.utils import timezone and put the USE_TZ = True in your project settings file.