Datetime python django model

An Introduction to Django DateTimeField

An Introduction to Django DateTimeField

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:

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_add saves instance of date-time into the database when the object is created.
  • auto_now saves instance of date-time into the database when the object is saved.
Читайте также:  Задачи уровня junior питон

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
id bigint 1
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.

Format Example
%Y-%m-%d %H:%M:%S 2021-12-12 11:44:59
%Y-%m-%d %H:%M:%S.%f 2021-12-12 11:44:59.000200
%Y-%m-%d %H:%M 2021-12-12 11:44
%m/%d/%Y %H:%M:%S 12/22/2021 11:44:59
%m/%d/%Y %H:%M:%S.%f 12/22/2021 11:44:59.000200
%m/%d/%Y %H:%M 12/22/2021 11:44
%m/%d/%y %H:%M:%S 12/22/21 11:44:59
%m/%d/%y %H:%M:%S.%f 12/22/21 11:44:59.000200
%m/%d/%y %H:%M 12/22/21 11:44

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.

Conclusion

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!

Recent Posts

Источник

Whats the correct format for django dateTime in models?

I am new to django and i am creating my first project. I created one app in which model i define one postgres datatime field but i always get error for this field when run migrate command. I used below value for datetime field in models.py but nothing happened

created=models.DateTimeField(default=timezone.now) created=models.DateTimeField(default='', blank=True, null=True) created=models.DateTimeField(blank=True, null=True) created=models.DateTimeField(default='0000-00-00 00:00:00', blank=True, null=True) 
LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True 
from django.db import models from django.utils import timezone # from django.contrib.auth.models import User # Create your models here. class Operator(models.Model): operator_code=models.CharField(unique=True, max_length=20) operator_name=models.CharField(max_length=60) operator_type=models.CharField(max_length=60) short_code=models.CharField(max_length=60) apiworld_code=models.CharField(max_length=20) apiworld_operatortype=models.CharField(max_length=20) active_api_id=models.IntegerField(default=1) ospl_commission=models.DecimalField(default=0.00, max_digits=11, decimal_places=2) apiworld_commission=models.DecimalField(default=0.00, max_digits=11, decimal_places=2) image=models.CharField(max_length=100) status=models.SmallIntegerField(default=1) updated=models.DateTimeField(default=timezone.now) created=models.DateTimeField(default=timezone.now) def __str__(self): return self.operator_code 

when i run ‘python manage.py migrate’ i got below error how to remove this ‘django.core.exceptions.ValidationError: [«‘0000-00-00 00:00:00′ value has the correct format (YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) but it is an invalid date/time.»]’

Источник

DateTimeField – Django Models

DateTimeField is a date and time field which stores date, represented in Python by a datetime.datetime instance. As the name suggests, this field is used to store an object of datetime created in python. The default form widget for this field is a TextInput . The admin uses two separate TextInput widgets with JavaScript shortcuts.

DateTimeField has the following extra optional arguments –

DateTimeField.auto_now

DateTimeField.auto_now_add

  • For DateTimeField: default=datetime.now – from datetime.now()
  • For DateTimeField: default=timezone.now – from django.utils.timezone.now()

Note: The options auto_now_add, auto_now, and default are mutually exclusive. Any combination of these options will result in an error.

Django Model DateTimeField Explanation

Illustration of DateTimeField using an Example. Consider a project named geeksforgeeks having an app named geeks .

Enter the following code into models.py file of geeks app.

Add the geeks app to INSTALLED_APPS

Now when we run makemigrations command from the terminal,

Python manage.py makemigrations

A new folder named migrations would be created in geeks directory with a file named 0001_initial.py

Thus, an geeks_field DateTimeField is created when you run migrations on the project. It is a field to store datetime.datetime python object.

How to use DateTimeField ?

DateTimeField is used for storing python datetime.datetime instance in the database. One can store any type of date and time using the same in the database. Let’s try storing a date in model created above.

DateTimeField django models

Now let’s check it in admin server. We have created an instance of GeeksModel.

Field Options

Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to DateTimeField will enable it to store empty values for that table in relational database.
Here are the field options and attributes that an DateTimeField can use.

Field Options Description
Null If True, Django will store empty values as NULL in the database. Default is False.
Blank If True, the field is allowed to be blank. Default is False.
db_column The name of the database column to use for this field. If this isn’t given, Django will use the field’s name.
Default The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.
help_text Extra “help” text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form.
primary_key If True, this field is the primary key for the model.
editable If False, the field will not be displayed in the admin or any other ModelForm. They are also skipped during model validation. Default is True.
error_messages The error_messages argument lets you override the default messages that the field will raise. Pass in a dictionary with keys matching the error messages you want to override.
help_text Extra “help” text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form.
verbose_name A human-readable name for the field. If the verbose name isn’t given, Django will automatically create it using the field’s attribute name, converting underscores to spaces.
validators A list of validators to run for this field. See the validators documentation for more information.
Unique If True, this field must be unique throughout the table.

Источник

Оцените статью