Django how do I use system timezone?

53 views Asked by At

For whatever reason, django is defaulting to use America/Chicago when TIME_ZONE is not specified.

My server runs in local devices, so the system timezones is all over the place and could change if people move around. Is there a way to accomplish this?

I just want os.environ["TZ"] to not be set, is this possible? Django on startup will set it to that variable to chicago

2

There are 2 answers

0
Hujaakbar On

'America/Chicago' is a default timezone.

When you set USE_TZ to False, Django defaults to using 'America/Chicago' . Interestingly, even if you set USE_TZ to True, unless you set TimeZone, django still defaults to using 'America/Chicago' timezone. Actually, starting Django 5.0, Time zone support is enabled by default.

Django sets environment variables so that its process runs in the default time zone. This happens regardless of the value of USE_TZ and of the current time zone.

Django automatically sets TZ environment variable.

I just want os.environ["TZ"] to not be set, is this possible?

Yes, it is possible. For that, You should set configuration manually.

But it is better to use timezone and set it to UTC (Django recommends to do so).

Even if your website is available in only one time zone, it’s still good practice to store data in UTC in your database. The main reason is daylight saving time (DST). Many countries have a system of DST, where clocks are moved forward in spring and backward in autumn. If you’re working in local time, you’re likely to encounter errors twice a year, when the transitions happen.

0
Selcuk On

You can set it to an empty string to use the system timezone:

...
TIME_ZONE = ""
...

You can also use the tzlocal library (I believe it is a Django dependency) to determine the current system timezone:

import tzlocal
...
TIME_ZONE = tzlocal.get_localzone_name()
...