📝 Django

Date Formats in Django

P
Author
Pyland
📅
Published
30.06.2026
⏱️
Reading time
1 min
👁️
Views
79
🌿
Level
Medium

Охватываемые темы: Date fields in a model, Working with dates in Python, Formatting in templates, Formatting in Python.

Date fields in a model

from django.db import models

class Task(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)  # set on creation
    updated_at = models.DateTimeField(auto_now=True)       # set on every save
    due_date = models.DateField(null=True, blank=True)

Working with dates in Python

from django.utils import timezone
from datetime import date, timedelta

now = timezone.now()            # aware datetime (with timezone)
today = timezone.localdate()    # local date

# Arithmetic
tomorrow = today + timedelta(days=1)
week_later = today + timedelta(weeks=1)

# Filtering
overdue = Task.objects.filter(due_date__lt=today, status='todo')

Formatting in templates

{{ task.created_at }}                    <!-- 2024-01-15 10:30:00+00:00 -->
{{ task.created_at|date:"d.m.Y" }}       <!-- 15.01.2024 -->
{{ task.created_at|date:"d M Y, H:i" }}  <!-- 15 Jan 2024, 10:30 -->
{{ task.created_at|timesince }}          <!-- 3 days ago -->
{{ task.due_date|timeuntil }}            <!-- in 2 days -->

Formatting in Python

from django.utils.formats import date_format

formatted = date_format(task.created_at, 'd.m.Y H:i')

# Standard Python strftime
task.created_at.strftime('%d.%m.%Y %H:%M')

Format settings

# settings.py
LANGUAGE_CODE = 'ru-ru'
USE_I18N = True
USE_L10N = True
USE_TZ = True

TIME_ZONE = 'Europe/Moscow'

# Formats for the ru locale
DATE_FORMAT = 'd.m.Y'
DATETIME_FORMAT = 'd.m.Y H:i'

Filtering by date

from django.utils import timezone

# Tasks due today
today = timezone.localdate()
Task.objects.filter(due_date=today)

# Tasks due this week
week_start = today - timedelta(days=today.weekday())
Task.objects.filter(due_date__range=[week_start, week_start + timedelta(days=6)])

# By year/month
Task.objects.filter(created_at__year=2024, created_at__month=1)

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

📝

pytest-django: Testing Django

Охватываемые темы: Installation, @pytest.mark.djangodb, Fixtures, Testing views.

📅 30.06.2026 👁️ 132
📝

What is an ORM

ORM (Object-Relational Mapping) is a technology that lets you work with a database through Python...

📅 30.06.2026 👁️ 124
📝

SQLite in Python: Persistent Memory for Agents

SQLite is a relational database built into Python. It stores data in a single file...

📅 30.06.2026 👁️ 78

Did you like the article?

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