In this Django DateTimeField guide, we will go through the basics of DateTimeField, use cases, and a couple of practical examples. After this blog post, you will be able to use DateTimeField successfully and with understanding, regardless of the problems, you may encounter when working with dates and times.
To better understand DateTimeField we will answer several questions:
- What are accepted DateTimeField inputs?
- How does DateTimeField save into the database?
- Why do we use DateTimeField?
And one practical example:
- Adding DateTimeField to model
Django DateTimeField and its parameters
All Django field model fields belong to the Field class and represent one column in the database, the same way Datetimefield works.
So what does DateTimeField represent in Django?
Django DateTimeField represents the timestamp with timezone in the database. That means it displays the date and time in one of the default formats (unless otherwise stated). Of course, the format of saving the DateTimeField can be changed, which we will show in one of the examples.
class DateTimeField(auto_now=False, auto_now_add=False, **options)
DateTimeField in Django has two optional parameters.
auto_now_addsaves instance of date-time into the database when the object is created.
auto_nowsaves instance of date-time into the database when the object is saved.
Quite often, the
default parameter is used with DateTimeField.
datetime = models.DateTimeField (default = datetime.now, blank = True)
NOTE - We do not call the datetime.now function (because the function's return value is returned to the default). We only give a reference to the function object so that function can be called when creating a new instance.
We will best understand DateTimeField if we look at a couple of examples.
Example – Adding DateTimeField to a model
I’ll use a Book model with the title as a CharField and published_date as DateTimeField.
from django.db import models class Book(models.Model): title = models.CharField(max_length=512) published_date = models.DateTimeField()
After applying migrations, data will look like this.
|Name||Data Type||Database Example|
|title||character varying||Django basics|
|published_datetime||timestamp with time zone||2021-12-31 15:25:00+01|
DateTimeField Input formats?
To add DateTime to the database, we need to know all the accepted formats. If we do not use a standard format, a ValidationError will be reported.
DateTimeField with Django ORM
We want to manage each attribute of the model for a variety of reasons, be it some calculations or something else. This is helped by the built-in Django ORM (Object-relational mapping). Django ORM sets specific built-in methods over the model by which we perform queries on the database in a user-friendly way.
So how does Django ORM behave with DateTimeField?
Using the filter method, I will show the methods we can use over the published_date attribute from the above book model.
# Filters books using the datetime object Book.objects.filter(published_datetime='2021-12-31 15:25:00+01') # Filters books that have a newer date than given Book.objects.filter(published_datetime__gt='2021-12-31') # Filters books that have an older date than given Book.objects.filter(published_datetime__lt='2021-12-31') # Filters the books depending on the day, month or year Book.objects.filter(published_datetime__day='31') Book.objects.filter(published_datetime__month='12') Book.objects.filter(published_datetime__year='2021') # Filters the book depending on the hour, minute, second Book.objects.filter(published_datetime__hour=3) Book.objects.filter(published_datetime__minute=25) Book.objects.filter(published_datetime__second=0) # Takes an integer value representing the day of the week from 1 (Sunday) to 7 (Saturday). Book.objects.filter(published_datetime__week_day=3) #Could be used with gte, gt, lte, lt, … Book.objects.filter(published_datetime__week_day__lte=2) # filters books in a given range Book.objects.filter(published_datetime__range=('2021-12-12', '2022-12-12')) # filters books by the given list of datetimes Book.objects.filter(published_datetime__in=['2021-12-31 15:25:00+01', '2022-02-01 07:00:00+01'])
DateTimeField Tips and Tricks
As updated_at and created_at are often inserted into a particular model to track activity, there is good practice in defining an abstract class containing these two fields.
The goal is to create a class that specific models will extend to avoid code duplication.
class TimeStampedModel(models.Model): """ An abstract base class model that provides self-updating 'created_at' and 'updated_at' field """ created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(auto_now=True, null=True) class Meta: abstract = True # Simply inherit TimeStampedModel class Book(TimeStampedModel): title = models.CharField(max_length=512)
Book model will have a title, created_at, and updated_at attributes.
NOTE - You may notice that created_at instead of auto_now_add = True uses default = timezone.now, they do the same thing for the given example.
More about Django DateTimeField in official Django documentation.
DateTimeField is a powerful feature for saving dates and times to a database. But because there is no official date format, problems often arise. For that reason,
dates and times are often subject to change. Therefore, it is necessary to read the official Django documentation every time a new version is released.
I hope you found this blog post helpful!