Охватываемые темы: 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)
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!