Django stores all DateTimeField values in UTC when USE_TZ=True. Conversion to local time happens at the display layer.
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)
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!