Opened 10 years ago
Closed 5 years ago
#23524 closed New feature (fixed)
Allow to set TIME_ZONE option on databases that support time zones.
Reported by: | Mactory | Owned by: | Aymeric Augustin |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | dev |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Ready for checkin | |
Has patch: | yes | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
When using a cursor created by django.db.connection.cursor() to execute a database function on a postgresql database, the timezone of the database connection is always set to UTC instead of using the specified TIME_ZONE.
This behavior brakes postgres' date_trunc
function, since it will truncate the hour to be 0 at UTC creating an offset from midnight at the local timestamp.
Example:
settings.py
TIME_ZONE = 'Europe/Berlin' # Offset +2 USE_TZ = TRUE
using date_trunc in a djago python shell:
./manage.py shell >>> from django.db import connection >>> cursor = connection.cursor() >>> cursor.execute("select date_trunc('month', TIMESTAMP WITH TIME ZONE '2014-09-14 04:10:00+02');") >>> unicode(cursor.fetchone()[0]) u'2014-09-01 00:00:00+00:00'
using date_tunc directly in psql:
psql db db=#select date_trunc('month', TIMESTAMP WITH TIME ZONE '2014-09-14 04:10:00+02'); date_trunc ------------------------ 2014-09-01 00:00:00+02 (1 row)
For executing custom functions for which no return value is needed, the following workaround does work:
>>> cursor.execute("SET TIMEZONE to %s;select date_trunc('month', TIMESTAMP WITH TIME ZONE '2014-09-14 04:10:00+02');SET TIMEZONE to 'UTC';", (settings.TIME_ZONE,))
Change History (9)
comment:1 by , 10 years ago
Resolution: | → invalid |
---|---|
Status: | new → closed |
comment:2 by , 5 years ago
Component: | contrib.postgres → Database layer (models, ORM) |
---|---|
Resolution: | invalid |
Status: | closed → new |
Summary: | Django postgres connection's timezone is always set to UTC. Breaks date_trunc function → Allow to set TIME_ZONE option on databases that support time zones. |
Triage Stage: | Unreviewed → Accepted |
Type: | Bug → New feature |
Version: | 1.6 → master |
Re-opened due to the comment.
comment:7 by , 5 years ago
Triage Stage: | Accepted → Ready for checkin |
---|
This is by design and it's documented. See also the discussions on django-developers leading to the implementation of time zone support in Django 1.4.
You may use
connection.ops.datetime_trunc_sql
(a private API), or look at what it returns and reimplement it by yourself.