0

My django project is correctly enable the timezone in settings.

However, the datetime field of Django ORM object is a naive datetime object as shown in Block 3.

The expected result should be same as the output of Block 4 without any manually conversion.

In [1]: from django.conf import settings
   ...: settings.USE_TZ, settings.TIME_ZONE
Out[1]: (True, 'Asia/Hong_Kong')

In [2]: from qms.models import Quota

In [3]: q = Quota.objects.get(pk=1)
   ...: q.create_date, q.write_date
Out[3]:
(datetime.datetime(2021, 3, 10, 17, 37, 42, 489818),
 datetime.datetime(2021, 3, 10, 17, 37, 42, 489818))

In [4]: from django.utils import timezone
   ...: timezone.make_aware(q.create_date,timezone.utc), \
   ...: timezone.make_aware(q.write_date, timezone.utc)
Out[4]:
(datetime.datetime(2021, 3, 10, 17, 37, 42, 489818, tzinfo=<UTC>),
 datetime.datetime(2021, 3, 10, 17, 37, 42, 489818, tzinfo=<UTC>))

Record in SQL

Column value
id 1
create_date 2021-03-10 17:37:42.489818+00
write_date 2021-03-10 17:37:42.489818+00
name email

Django Model Definition

class Quota(models.models):
    name = models.CharField(max_length=255)
    create_date = models.DateTimeField(auto_now_add=True)
    write_date = models.DateTimeField(auto_now=True)

The PostgreSQL database schema and settings, Table "public.qms_quota"

Column Type Modifiers
id integer not null default nextval('qms_quota_id_seq'::regclass)
create_date timestamp with time zone not null
write_date timestamp with time zone not null
name character varying(255) not null
SHOW TIMEZONE;
 TimeZone
----------
 UTC

Questions

  1. How can I get the timezone-aware datetime object directly without any conversion?
  2. Or the manual conversion is expected ?
1
  • This is unusual behavior, so I'm assuming that your application or database has changed at some point? Can you replicate this with a fresh database? Also, please show the actual database values (not the Python objects) for your example (pk=1). Commented Mar 11, 2021 at 5:14

2 Answers 2

2

The root-cause is a bug from a connection pool library django_postgrespool2==2.0.1.

When you use the your connection engine with "django_postgrespool2", it will NOT correctly handle the timezone settings. Releated Issue

TLDR: use engine django.db.backends.postgresql

Sign up to request clarification or add additional context in comments.

Comments

0

You can use django.utils.timezone.localtime to convert the datetime received from the DB to localtime:

from django.utils.timezone import localtime
q = Quota.objects.get(pk=1)
print(localtime(q.create_date), localtime(q.write_date))

1 Comment

i want to get the aware datetime object without any conversion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.