๐Ÿ“ Django

Timezones in Django

P
Author
PyLand Team
๐Ÿ“…
Published
30.06.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
286
๐ŸŒฟ
Level
Medium

Reliable timezone handling requires aware datetime values, UTC storage, and conversion to local time at the display boundary.

Configuration

# settings.py
USE_TZ = True                    # enable timezone support (recommended)
TIME_ZONE = 'Europe/Moscow'      # server timezone

Aware vs Naive Datetime

from django.utils import timezone
from datetime import datetime

# Aware โ€” datetime with timezone info (correct when USE_TZ=True)
now = timezone.now()  # UTC datetime with tzinfo

# Naive โ€” without timezone info (dangerous!)
naive = datetime.now()  # local time without tzinfo

Working with Dates

from django.utils import timezone

# Current time (UTC)
now = timezone.now()

# Current date in the local timezone
today = timezone.localdate()

# Convert to local time
local_now = timezone.localtime(now)

# Convert an aware datetime
from django.utils.timezone import make_aware
import pytz

moscow = pytz.timezone('Europe/Moscow')
aware = make_aware(datetime(2024, 1, 15, 12, 0), moscow)

Storage in the Database

Django stores all DateTimeField values in UTC when USE_TZ=True. Conversion to local time happens at the display layer.

In Templates

{# Automatically converts to the local timezone #}
{{ task.created_at|date:"d.m.Y H:i" }}

{# Force a specific timezone in the template #}
{% load tz %}
{% timezone "Europe/Moscow" %}
  {{ task.created_at }}
{% endtimezone %}

Switching Timezone per User

from django.utils import timezone

def set_timezone(request):
    if request.method == 'POST':
        tz = request.POST.get('timezone')
        request.session['django_timezone'] = tz
    return redirect('/')
# middleware
class TimezoneMiddleware:
    def __call__(self, request):
        tzname = request.session.get('django_timezone')
        if tzname:
            timezone.activate(pytz.timezone(tzname))
        else:
            timezone.deactivate()
        return self.get_response(request)

Your reaction to the article

๐Ÿ’ฌ Comments (0)

๐Ÿ” Sign in to leave a comment
๐Ÿšช Login
๐Ÿ’ญ

No comments yet

Be the first to share your opinion about this article!

๐Ÿ”— Similar

Similar articles

Continue learning with these materials

๐Ÿ“

settings.py: Django Configuration

settings.py is the central configuration file for a Django project.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 316
๐Ÿ“

CSRF Protection in Django

CSRF (Cross-Site Request Forgery) is an attack in which an adversary tricks the user's browser...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 294
๐Ÿ“

Django Migrations

A migration is a file describing changes to the database schema. Django tracks the state...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 286

Did you like the article?

Subscribe to our updates and be the first to receive new articles. Grow with PyLand!