Django postgres connection, SET timezone for psycopg2

2.3k views Asked by At

In django settings.py I have TIME_ZONE = 'Asia/Tbilisi'

I have same timezone for postgres also

and separately, both works correctly.

Though, in Django, when I run raw queries like:

from django.db import connection
...
cursor = connection.cursor()
cursor.execute("select localtimestamp(0)")
res = cursor.fetchall()

This shows datetime with UTC time zone.

Probably this is caused by psycopg2 connection settings? because this:

print( connection.cursor().connection.get_parameter_status("TimeZone") )

shows: UTC.

Question: How can I change this connection settings and SET needed timezone?

1

There are 1 answers

0
AdamKG On BEST ANSWER

Issue a SET timezone TO 'Asia/Tbilisi'; query first, or set the PGTZ environment variable (using os.environ if you need to do it from python) before opening the connection. You can also issue an ALTER DATABASE or ALTER ROLE and set the timezone by default, as noted in the linked docs for PGTZ, but I tend to avoid that because it's easy to forget to do it for new DBs/users (& it also only applies for new connections; long-running ones will have the TZ that was the default when they connected).