Python Django Set Timezone

In this Django Tutorial, you will learn about Python Django Set Timezone where you understand the concept of timezone.

Also, you will understand the importance of time zones in the Django applications. Additionally, you learn how to set a timezone in your Django project.

Finally, you understand how to set the timezone for a specific region.

Python Django Set Timezone

A time zone is just a region of the globe where everyone is on the same clock. However, due to something called daylight savings time, a given time zone may not follow the same time throughout the year.

Because of these issues, the globe agreed to adopt a universal time standard that remains constant regardless of where you are or what time of year it is. The coordinated universal time, or UTC, is the name for this.

For example, I live in India, which is 5 hours and 30 minutes ahead of UTC, so the time was 10:32:10 PM UTC+5:30 at this time. 10:32:10 PM GMT+5:30 is another way to write it. There is no difference between GMT and UTC in terms of time; nonetheless, GMT is a time zone, and UTC is a time-measurement standard.

Why Timezone is important?

When you properly handle the time zones it makes sure that the user sees date and time data according to their location or wherever they live.

The time zones are very important in the application or project where timely operations are performed such as the airline ticket booking system, and an e-commerce application such as Amazon for time-limited offers.

Also, check: How to Get Current Time in Django

Python Django Set Timezone Settings

For saving information in the database, Django recommends using UTC. Even if your website is only accessible in a one-time zone, storing data in UTC in your database is still a good strategy. Daylight Saving Time is the primary reason for this.

DST is a time-keeping system in which clocks are pushed forward in the spring and backward in the autumn in many nations. If you work in local time, you’re likely to run into problems twice a year when the clocks change.

READ:  How to use np.argsort in Descending order in Python [2 ways]

When you build a Django project, it automatically creates a file called setting.py in your project directory.

Let’s build a Django project and see how to change the time zones.

First, open your command prompt and create a virtual environment named ‘env’.

python -m venv env

Activate the environment.

env\Scripts\activate

Install the latest version of Django.

pip install django

Create a Django project named ‘django_timezones’.

django-admin startproject django_timezones

Change the directory to the Django project.

cd django_timezones

Create a Django app named ‘timezone_app’.

python manage.py startapp timezone_app
Python Django Set Timezone Settings Project Setup

Add the created app in the INSTALLED_APPS section of the setting.py file of your Django project ‘django_timzeons’ as shown below.

Python Django Set Timezone Settings Installed Apps

Open the urls.py file of your Django project and add the following lines of code.

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('timezone_app.urls'))
]
Python Django Set Timezone Settings URL

Now open your project in Visual Studio Code.

After that open the Django project named ‘django_timezones’ and there is a file called setting.py.

Python Django Set Timezone Settings File

You only need to configure a few things in your Django application’s settings.py to set the timezone.

TIME_ZONE = '<Time zone of your choice>'
USE_TZ = True
Python Django Set Timezone Settings

By default, the Time zone is UTC, and USE_TZ is set to True, which ensures that using a datetime.now() function in your Django application creates time in UTC.

The UTC stands for Coordinated Universal Time and based on this time standard world controls the clocks and times.

Read: How to Create model in Django

Python Django Set Timezone UTC

Now, in this section, we will discuss how to set the timezone to UTC. For the demonstration of this topic, we are using the Delivery model in Django. The model contains the following data.

Python Django set timezone
Delivery Model

Django’s timezone is set to UTC by default. If your timezone is not UTC, you can change it using the procedure below:

  • Open the setting.py file in the directory of our project.
  • Internationalization can be found by scrolling down the file.
  • TIME ZONE will appear under this.
  • Set it to ‘UTC’.

Command to set timezone:

TIME_ZONE='UTC'

Now you may start the server and log in to the admin interface. After that, open your Delivery model, and you’ll notice that the time has been changed to UTC.

django set timezone to utc
TIME_ZONE = UTC

Read: Python Django get admin password

Python Django Set Timezone To EST

Now, in this section, we will discuss how to set the timezone to EST. To illustrate this topic, we are using the Delivery model in Django. The model contains the following data and here the time zone used in this model is UTC, by default.

django set timezone to utc
Delivery Model

To set the timezone, you must first set up a few things in your Django application’s settings.py, which are as follows:

READ:  Pandas Replace Multiple Values in Column based on Condition in Python [4 Methods]

Command to set timezone:

TIME_ZONE = 'EST'

You can now start the server and access the administrative interface. When you open your Delivery model, you’ll see that the time has been changed to EST.

Here is the output, which clearly shows that the time zone changes to EST.

django set timezone to est
TIME_ZONE = EST

Read: If statement in Django template

Python Django Set Timezone To IST

Now, in this section, we will discuss how to set the timezone to IST. To illustrate this topic, we are using the Delivery model in Django. The model contains the following data and here the time zone used in this model is UTC, by default.

django set timezone to utc
Delivery Model

Here IST means Indian Standard Time, which is Asia/Kolkata as per the time zone. And, to set the timezone, you must first set up a few things in your Django application’s settings.py, which are as follows:

Command to set timezone:

TIME_ZONE = 'Asia/Kolkata'

You can now start the server and access the administrative interface. When you open your Delivery model, you’ll see that the time has been changed to IST.

Here is the output, which clearly shows that the time zone changes to IST.

django set timezone ist
TIME_ZONE = IST

Read: Get URL parameters in Django

Python Django Set Timezone For User

In this section, we’ll learn how to set the timezone for users based on their local timestamp. If you want to create timestamps in the local time zone. Do the following settings in the settings.py file of the Django project.

USE_TZ = FALSE
Python Django Set Timezone For User USE_TZ

If you set USE_TZ to False, Django assumes your application doesn’t care about time zones. It refers to the location where the Django application is hosted; for example, if you run it locally on your computer, it will use that time.

By default, the TIME_ZONE is set to ‘UTC’, and the USE_TZ is set to ‘True’. So, when we fetch the time it shows the time in UTC.

Let’s see an example to understand the concept clearly:

Open the views.py file of your Django app ‘timezone_app’ and add the following lines of code.


from django.http import HttpResponse
from django.utils import timezone


def home(request):
    current_time = timezone.now().strftime('%H:%M:%S')
    html = "<html><body><b>Current Time Value:</b> %s</body></html>" % current_time
    return HttpResponse(html)
Python Django Set Timezone For User Views

In the above example, we have imported the timezone class from Django.utils module. Next, we have created a view with the name home. In this view, we are using the timezone.now().strftime() method to store the current time value in a variable. And then, we are using the variable to return the current time value as an HTTP response.

READ:  NumPy Create an Empty Array in Python [3 Examples]

After that create a urls.py file in your Django app ‘timzone_app’ and add the following URL path.

from django.urls import path
from .views import *
urlpatterns = [
    path('', home,name='home'),
]
Python Django Set Timezone For User App URL

Open your terminal and run the following command to migrate the default model that comes with Django.

python manage.py migrate

Run the Django server using the below command.

python manage.py runserver

Now, if we run the development server and open the URL ‘http://127.0.0.1:8000/’ in your browser, you see the following output.

Python Django Set Timezone For User

If your user belongs to a specific region such user who lives in New York, set the timezone for that user.

Open the setting.py file of your Django project ‘django_timezones’ and set the TIME_ZONE to ‘American/New_York’ and USE_TZ to True as shown in the below picture.

Python Django Set Timezone For User New York

Open the views.py file of your Django app ‘timezon_app’ and modify the view home by adding the following lines of code:

from django.http import HttpResponse
from django.utils import timezone



def home(request):
    current_time = timezone.now().strftime('%H:%M:%S')
    html = "<html><body><b>Current Time Value:</b> %s</body></html>" % current_time
    return HttpResponse(html)
Python Django Set Timezone For User View Home

Now again open the URL ‘http://127.0.0.1:8000/’ in your browser, and you get the following output.

Python Django Set Timezone For User American New York

The above time shows according to the timezone ‘American/New_York’.

Conclusion

In this Django tutorial, you learned how to set time zones in a Django project and also learned the importance of time zones. Finally, you build the Django project and set the timezone to a different time.

You may also like to read the following Django tutorials.