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 timezone in the Django applications. Additonally you learn how to set timezone in your Django project.

Finally you understand how to set 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 Importand?

When you properly handle the time zones it make sure that the user see date and time data according to their location or whereever they live.

The time zons are very important in the appliacatin or project where timely operation are performed such as airline ticket booking system, an e-commerce application such as amazone 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.

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

Let’s build Django project and see how to change the timezones.

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 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 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 on the basis of 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. And 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, 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. And 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:

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. And 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 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 the 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.

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

Opne your terminal and run the following command to migrate the defaul 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 you user belong to speicific region such user lives in New York, to 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, you get the following output.

Python Django Set Timezone For User American New York

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

Conclusion

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

You may also like to read the following Django tutorials.


电子产品 排行榜


Gurmandise 哆啦A梦 铜锣烧 手机手环

IT電腦補習 java補習 為大家配對電腦補習,IT freelance, 私人老師, PHP補習,CSS補習,XML,Java補習,MySQL補習,graphic design補習,中小學ICT補習,一對一私人補習和Freelance自由工作配對。
立刻註冊及報名電腦補習課程吧!

facebook 查詢:
24 hours enquiry facebook channel :
https://www.facebook.com/itteacheritfreelance/?ref=aymt_homepage_panel

Be the first to comment

Leave a Reply

Your email address will not be published.


*