问题:
Postgresql 时区设置为“UTC”
/etc/postgresql/15/main/conf.d/local.conf:
log_timezone = Europe/Warsaw
timezone = UTC
数据库已更改:
ALTER DATABASE example_database SET TIMEZONE TO 'Europe/Warsaw';
Postgresql 用户设置了自己的 time_zone
SELECT rolconfig FROM pg_roles WHERE rolname = 'someuser';
{TimeZone=Europe/Warsaw}
设置.py
USE_TZ = True
TIME_ZONE = 'Europe/Warsaw'
但是在连接期间 postgresql 正在获取:
LOG: statement: SELECT set_config('TimeZone', 'UTC', false)
我做错了什么???
找到了!!!
我必须深入研究 postgresql 库并发现这个:
/site-packages/django/db/backends/base/base.py:
def timezone(self):
"""
Return a tzinfo of the database connection time zone.
This is only used when time zone support is enabled. When a datetime is
read from the database, it is always returned in this time zone.
When the database backend supports time zones, it doesn't matter which
time zone Django uses, as long as aware datetimes are used everywhere.
Other users connecting to the database can choose their own time zone.
When the database backend doesn't support time zones, the time zone
Django uses may be constrained by the requirements of other users of
the database.
"""
if not settings.USE_TZ:
return None
elif self.settings_dict["TIME_ZONE"] is None:
return datetime.timezone.utc
else:
return zoneinfo.ZoneInfo(self.settings_dict["TIME_ZONE"])
解决方案是:
设置.py:
DATABASES = {
'default': {
# Add 'postgresql_psycopg2','postgresql', 'mysql', 'sqlite3' or 'oracle'.
'ENGINE': 'django.db.backends.postgresql_psycopg2',
# Or path to database file if using sqlite3.
'NAME': env('DATABASE_NAME'),
# Not used with sqlite3.
'USER': env('DATABASE_USER'),
# Not used with sqlite3.
'PASSWORD': env('DATABASE_PASSWORD'),
# Set to empty string for localhost. Not used with sqlite3.
'HOST': env('DATABASE_HOST', default='127.0.0.1'),
# Set to empty string for default.
'PORT': env('DATABASE_PORT', default='5432'),
'TIME_ZONE': 'Europe/Warsaw',
# Not used with sqlite3.
},