python 18 lines · 1 tab

Django timezone-aware datetime handling

Priya Sharma Jan 2026
1 tab
from django.db import models
from django.utils import timezone


class Event(models.Model):
    name = models.CharField(max_length=200)
    start_time = models.DateTimeField()
    created_at = models.DateTimeField(auto_now_add=True)

    def is_upcoming(self):
        """Check if event is in the future."""
        return self.start_time > timezone.now()

    def local_start_time(self, tz_name='America/New_York'):
        """Get start time in specific timezone."""
        import pytz
        tz = pytz.timezone(tz_name)
        return timezone.localtime(self.start_time, tz)
1 file · python Explain with highlit

Django stores datetimes as UTC in the database when USE_TZ=True. I use timezone.now() instead of datetime.now() to get aware datetimes. The timezone.localtime() converts UTC to user's timezone for display. For user input, I use timezone.make_aware() to add timezone info. Template filters like {{ value|date }} respect TIME_ZONE setting. I'm careful with auto_now_add and auto_now as they always use UTC. For scheduling, I use django-celery-beat with timezone-aware crontabs. This prevents subtle bugs around DST transitions and international users.


Related snips

python
import os
import stat

for root, _dirs, files in os.walk('/etc'):
    for name in files:
        path = os.path.join(root, name)

Python security audit script for exposed risky filesystem state

python auditing host-security
by Kai Nakamura 1 tab
python
class Product(models.Model):
    name = models.CharField(max_length=200)
    slug = models.SlugField(blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    cost = models.DecimalField(max_digits=10, decimal_places=2)
    margin = models.DecimalField(max_digits=5, decimal_places=2, blank=True)

Django model signals vs overriding save

django python models
by Priya Sharma 2 tabs
python
from django.urls import path
from . import views

app_name = 'blog'

urlpatterns = [

Django URL namespacing and reverse lookups

django python urls
by Priya Sharma 3 tabs
python
import graphene
from graphene_django import DjangoObjectType
from blog.models import Post, Comment


class PostType(DjangoObjectType):

Django GraphQL with Graphene

django python graphql
by Priya Sharma 2 tabs
python
from django.db.models import Count, Avg, Sum, Q, F
from django.views.generic import TemplateView
from products.models import Product, Order, OrderItem


class DashboardView(TemplateView):

Django aggregation with annotate for statistics

django python database
by Priya Sharma 1 tab
python
from rest_framework import permissions


class IsOwner(permissions.BasePermission):
    """Allow only object owner to access."""

Django REST Framework permissions and authorization

django python rest
by Priya Sharma 2 tabs

Share this code

Here's the card — post it anywhere.

Django timezone-aware datetime handling — share card
Link copied