Inconsistencies in django timezone object.

We are using the timezone provided by Django for "Asia/Kuwait" and it has been working as expected since today.

We checked the timezone object is not aligned with global settings. We compared it with Python datetime object and surprisingly, the timezone object from Django was failing but datetime object was accurate.

This leaves me with the question why is that? Am I doing something wrong. ?

Let’s check this out, I compared both in our linux server where django project is being hosted

# Django 4.2 LTS
$ python manage.py shell 
Python 3.9.16 (main, Sep  8 2023, 00:00:00)
[GCC 11.4.1 20230605 (Red Hat 11.4.1-2)] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.conf import settings
>>> settings.TIME_ZONE
'Asia/Kuwait'
>>> from django.utils import timezone
>>> timezone.now()
datetime.datetime(2023, 12, 9, 10, 45, 48, 410034, tzinfo=datetime.timezone.utc) #Inaccurate should have 13:45:48
>>> timezone.get_current_timezone()
zoneinfo.ZoneInfo(key='Asia/Kuwait') # It's also have information from settings but still inaccurate
>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2023, 12, 9, 13, 46, 59, 432251) # accurate 13:46:59 HH:MM:SS
>>>

Can you please help me understand why this can happen, do you think relying on a timezone object from Django is a good decision?

Well, this is well-stated on the documentation of the django.utils.timezone.now function:

  • If USE_TZ is True, this will be an aware datetime representing the current time in UTC. Note that now() will always return times in UTC regardless of the value of TIME_ZONE; you can use localtime() to get the time in the current time zone.

The main difference is that the datetime.datetime.now() returns a naive datetime object, when the django util returns an aware datetime.

1 Like