Let’s set timezone in Django. It is easy to configure and you will learn where and how to do itfrom this article.
Setting the time_zone
By default, the application written in Django set the TIME_ZONE variable, responsible for the definition of the local time zone, to ‘America / Chicago’. You can configure it by default in the settings.py file.
In newer versions of Django, the settings.py file already contains an entry:
TIME_ZONE = 'UTC'
You may want to change that. First you will need this Wikipedia link to get timezone names.
You can change your timezone to eg.:
TIME_ZONE = 'US/Central'
To apply timezone you need also to set below variable time zone.
USE_TZ = True
How to set a custom timezone in Django
In addition to setting the default timezone, you can also set a custom timezone for your Django application. To do this, you can use the TIME_ZONE and USE_TZ variables in the settings.py file.
The TIME_ZONE variable specifies the name of the timezone that you want to use. You can get a list of timezone names from the Wikipedia link.
The USE_TZ variable specifies whether or not you want to use timezones in your Django application. If you set USE_TZ to True, Django will use the timezone that you specified in the TIME_ZONE variable to convert between UTC and local time.
For example, the following code will set the timezone to US/Central and enable timezone support:
TIME_ZONE = 'US/Central' USE_TZ = True
After setting the timezone, you need to restart your Django application for the changes to take effect.
Key takeaways
You can set the timezone for your Django application by using the TIME_ZONE and USE_TZ variables in the settings.py file.
The TIME_ZONE variable specifies the name of the timezone that you want to use.
The USE_TZ variable specifies whether or not you want to use timezones in your Django application.
If you set USE_TZ to True, Django will use the timezone that you specified in the TIME_ZONE variable to convert between UTC and local time.
FAQs
What is the difference between TIME_ZONE and USE_TZ?
The TIME_ZONE variable specifies the name of the timezone that you want to use, while the USE_TZ variable specifies whether or not you want to use timezones in your Django application.
What happens if I don’t set the TIME_ZONE variable?
If you don’t set the TIME_ZONE variable, Django will use the UTC timezone by default.
What happens if I set the USE_TZ variable to False?
If you set the USE_TZ variable to False, Django will not use timezones in your Django application. This means that all dates and times will be stored in UTC.