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 |
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
- How can I get the timezone-aware datetime object directly without any conversion?
- Or the manual conversion is expected ?
pk=1).