Set the Timezone in Django

While working on numerous Django projects that serve users across different time zones. Handling time zones correctly is important, especially when your application deals with date and time data for users in multiple regions.

In this article, I’ll walk you through how to set and manage time zones in Django effectively. I’ll share practical examples and best practices based on real-world projects, so you can implement timezone-aware features confidently.

How Django Handles Timezones by Default

By default, Django has timezone support disabled. This means:

  • All datetime objects are naive (no timezone info).
  • The TIME_ZONE setting defines the default timezone for your project, but does not convert datetime objects automatically.

To build timezone-aware Django apps, you need to enable timezone support and configure it properly.

Read How to Add Items to Cart in Django in Python?

Method 1: Set Timezone in Django Settings

The simplest way to set a timezone in Django is by configuring the TIME_ZONE setting in your settings.py file.

Here’s how I do it for projects targeting users across the USA:

# settings.py

# Set the default timezone to US Eastern Time (change as needed)
TIME_ZONE = 'America/New_York'

# Enable timezone support
USE_TZ = True
  • TIME_ZONE sets the default timezone for your project.
  • USE_TZ = True tells Django to use timezone-aware datetimes.

Django uses the IANA timezone database, so you can set TIME_ZONE to any valid timezone string like 'America/Los_Angeles' or 'America/Chicago'.

I executed the above example code and added the screenshot below.

time zone django

Check out Payment Gateway Integration with Django

Method 2: Use Django’s Timezone Module for Timezone-Aware Dates and Times

Once timezone support is enabled, you should use Django’s timezone module to work with aware datetime objects.

Here’s an example of how to get the current time in the default timezone:

from django.utils import timezone

def get_current_time():
    now = timezone.now()
    print(f"Current time (timezone-aware): {now}")
    return now

timezone.now() returns the current time with timezone info attached, respecting your TIME_ZONE setting.

I executed the above example code and added the screenshot below.

django timezone

Read Compare Two Integers in Python Django

Method 3: Handle User-Specific Timezones

If your app serves users in different US time zones, you might want to display times in their local time zone rather than the server’s default.

Here’s how I handle this:

  1. Store all datetime values in UTC in the database (Django does this automatically if USE_TZ=True).
  2. Detect or let users select their timezone (e.g., 'America/Denver' for Mountain Time).
  3. Convert UTC datetimes to the user’s timezone before displaying.

Example:

from django.utils import timezone
import pytz

def convert_to_user_timezone(utc_dt, user_timezone_str):
    user_tz = pytz.timezone(user_timezone_str)
    user_time = utc_dt.astimezone(user_tz)
    print(f"Time in user timezone ({user_timezone_str}): {user_time}")
    return user_time

Usage:

utc_now = timezone.now()
user_time = convert_to_user_timezone(utc_now, 'America/Denver')

This approach ensures your users always see times relevant to their location.

Check out Build a Chat App in Django

Method 4: Set Timezone Per Request Using Middleware

For dynamic timezone handling per user, you can create middleware that activates the user’s timezone on each request.

Here’s a simple example:

from django.utils import timezone
import pytz

class TimezoneMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Example: Fetch user timezone from session or profile
        user_timezone = request.session.get('user_timezone', 'America/New_York')
        timezone.activate(pytz.timezone(user_timezone))
        response = self.get_response(request)
        timezone.deactivate()
        return response

Add this middleware to your MIDDLEWARE list in settings.py:

MIDDLEWARE = [
    # ... other middleware ...
    'your_project.middleware.TimezoneMiddleware',
]

This method automatically adjusts the timezone for each request based on user preference.

Read How to Deploy an AI Model with Django

Additional Tips for Working with Timezones in Django

  • Always store datetimes in UTC in your database.
  • Use Django’s timezone.now() instead of Python’s datetime.now() for timezone awareness.
  • When displaying dates in templates, use Django’s localtime filter to convert to the current active timezone.
  • Consider using third-party packages like django-timezone-field for easier timezone selection and storage.

Setting time zones in Django can seem tricky at first, but once you understand the basics and best practices, it becomes straightforward. Using the methods above, you can build applications that handle date and time data correctly for users across all US time zones.

If you want to dive deeper or have questions, feel free to reach out. Timezone handling is a critical skill for any Django developer, and mastering it will make your applications more robust and user-friendly.

Related articles you may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.