Opened 5 months ago

Closed 5 months ago

Last modified 5 months ago

#35240 closed Bug (needsinfo)

Django doesn't set Postgres timezone to UTC when using psycopg3

Reported by: Fabi Owned by: nobody
Component: Uncategorized Version: 4.2
Severity: Normal Keywords:
Cc: Fabi, Mariusz Felisiak, Florian Apolloner, Simon Charette Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Fabi)

Configuration uses USE_TZ=True and database defaults to America/New_York. I would expect the connection then being set to UTC, but it is not changed:

In [4]: connections["default"].cursor()
Out[4]: zoneinfo.ZoneInfo(key='America/New_York')

The wrapper and the psycopg3 timezone adapter both think its UTC though:

In [5]: connections["default"].timezone
Out[5]: datetime.timezone.utc

In [6]: connections["default"].cursor().connection.adapters.get_loader(TIMESTAMPTZ_OID, Format.TEXT).timezone
Out[6]: datetime.timezone.utc

Looking at the code I think the problem is that the adapter gets initialized with self.timezone which then gets compared with self.timezone later again, resulting in a no-op:

Change History (6)

comment:1 by Fabi, 5 months ago

Description: modified (diff)

comment:2 by Fabi, 5 months ago

Version: 5.04.2

comment:3 by Natalia Bidart, 5 months ago

Cc: Mariusz Felisiak Florian Apolloner Simon Charette added

Hello Fabi, thank you for your report.

Could you please provide details about your settings for DATABASES? From these docs:

Default: None
A string representing the time zone for this database connection or None [...]
When USE_TZ is True, reading datetimes from the database returns aware datetimes with the timezone set to this option’s value if not None, or to UTC otherwise.

Also, could you please try using latest Django 5.0 or from the main branch? Django 4.2 is not receiving bug fixes any more so we'd need to confirm is this is still an issue in newer/supported versions.

In any case, it's unexpected (to me) that from the source links you provided, get_adapters_template takes two parameters use_tz, timezone but only timezone is used.

comment:4 by Natalia Bidart, 5 months ago

Resolution: needsinfo
Status: newclosed

comment:5 by Fabi, 5 months ago

DATABASES does not have a TIME_ZONE set.

While there might be other bugs in this specific code, I was able to fix this specific problem by defaulting the database to UTC.

I'll leave it up to you if you want to close this or leave it open for further investigation.

comment:6 by David Sanders, 5 months ago

Tested on current main, seems to work as expected 🤷‍♂️:

>>> settings.USE_TZ
>>> settings.TIME_ZONE
>>> pprint.pprint(settings.DATABASES['default']['TIME_ZONE'])
>>> connections['default'].cursor()
Note: See TracTickets for help on using tickets.
Back to Top