django.db.models DateTimeField Example Code

DateTimeField is a frequently-used attribute on Model classes when defining date- and time-based database columns with the Django ORM.

The Django project has great documentation for DateTimeField and all of the other column fields.

Note that DateTimeField is defined within the django.db.models.fields module but is typically referenced from django.db.models rather than including the fields module reference.

Example 1 from django-push-notifications

django-push-notifications is a Django app for storing and interacting with push notification services such as Google's Firebase Cloud Messaging and Apple Notifications. The django-push-notification project's source code is available open source under the MIT license.

[django-push-notifications / push_notifications /](

from __future__ import unicode_literals

from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _

from .fields import HexIntegerField

    ("FCM", "Firebase Cloud Message"),
    ("GCM", "Google Cloud Message"),

    ("CHROME", "Chrome"),
    ("FIREFOX", "Firefox"),
    ("OPERA", "Opera"),

class Device(models.Model):
    name = models.CharField(max_length=255, verbose_name=_("Name"), 
                            blank=True, null=True)
    active = models.BooleanField(
        verbose_name=_("Is active"), default=True,
        help_text=_("Inactive devices will not be sent notifications")
    user = models.ForeignKey(
        SETTINGS["USER_MODEL"], blank=True, null=True, 
    date_created = models.DateTimeField(
        verbose_name=_("Creation date"), auto_now_add=True, null=True
    application_id = models.CharField(
        max_length=64, verbose_name=_("Application ID"),
            "Opaque application identity, should be filled in for"
            " multiple key/certificate access"
        blank=True, null=True

    class Meta:
        abstract = True

    def __str__(self):
        return (
            str(self.device_id or "") or
            "%s for %s" % (self.__class__.__name__, 
                           self.user or "unknown user")

## source code continues here without further DateTimeField examples

Example 2 from AuditLog

Auditlog (project documentation) is a Django app that logs changes to Python objects, similar to the Django admin's logs but with more details and output formats. Auditlog's source code is provided as open source under the MIT license.

django-auditlog / src / auditlog /

from __future__ import unicode_literals

from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Model, NOT_PROVIDED, DateTimeField
from django.utils import timezone
from django.utils.encoding import smart_text

def track_field(field):
    Returns whether the given field should be tracked by Auditlog.
    Untracked fields are many-to-many relations and relations to 
    the Auditlog LogEntry model.
    :param field: The field to check.
    :type field: Field
    :return: Whether the given field should be tracked.
    :rtype: bool
    from auditlog.models import LogEntry
    # Do not track many to many relations
    if field.many_to_many:
        return False

    # Do not track relations to LogEntry
    if getattr(field, 'remote_field', None) is not None and \
        field.remote_field.model == LogEntry:
        return False

    # 1.8 check
    elif getattr(field, 'rel', None) is not None and \ == LogEntry:
        return False

    return True

def get_fields_in_model(instance):
    Returns the list of fields in the given model instance. 
    Checks whether to use the official _meta API or use the raw
    data. This method excludes many to many fields.
    :param instance: The model instance to get the fields for
    :type instance: Model
    :return: The list of fields for the given model (instance)
    :rtype: list
    assert isinstance(instance, Model)

    # Check if the Django 1.8 _meta API is available
    use_api = hasattr(instance._meta, 'get_fields') and \

    if use_api:
        return [f for f in instance._meta.get_fields() if track_field(f)]
    return instance._meta.fields

def get_field_value(obj, field):
    Gets the value of a given model instance field.
    :param obj: The model instance.
    :type obj: Model
    :param field: The field you want to find the value of.
    :type field: Any
    :return: The value of the field as a string.
    :rtype: str
    if isinstance(field, DateTimeField):
        # DateTimeFields are timezone-aware, so we need 
        # to convert the field to its naive form before we 
        # can accuratly compare them for changes.
            value = field.to_python(getattr(obj,, 
            if value is not None and settings.USE_TZ and \
                not timezone.is_naive(value):
                value = timezone.make_naive(value, 
        except ObjectDoesNotExist:
            value = field.default if field.default \
                is not NOT_PROVIDED else None
            value = smart_text(getattr(obj,, None))
        except ObjectDoesNotExist:
            value = field.default if field.default \
                is not NOT_PROVIDED else None

    return value

## ... source file continues here without further DateTime examples ...
1. Introduction 2. Development Environments 3. Data 4. Web Development 5. Deployment 6. DevOps Changelog What Full Stack Means About the Author Future Directions Page Statuses Django ExtensionsDjango Example Codedjango.apps.config AppConfigdjango.conf settingsdjango.conf.urls.urldjango.contrib.admindjango.contrib.admin.filters SimpleListFilterdjango.contrib.admin.sites registerdjango.contrib.auth.decorators login_requireddjango.contrib.auth get_user_modeldjango.contrib.auth.hashers make_passworddjango.core.exceptions ImproperlyConfigureddjango.core.mail.messages BaseCommanddjango.db.models AutoFielddjango.db.models BooleanFielddjango.db.models CharFielddjango.db.models DateFielddjango.db.models DateTimeFielddjango.db.models FileFielddjango.db.models ForeignKeydjango.db.models GenericIPAddressFielddjango.db.models ImageFielddjango.db.models IntegerFielddjango.db.models Modeldjango.db.models PositiveIntegerFielddjango.db.models PositiveSmallIntegerFielddjango.db.models.signaldjango.db.models SlugFielddjango.db.models SmallIntegerFielddjango.db.models TextFielddjango.db OperationalErrordjango.dispatch Signaldjango.formsdjango.forms BooleanFielddjango.forms CharFielddjango.forms ChoiceFielddjango.forms DateFielddjango.forms DateTimeFielddjango.forms EmailFielddjango.forms IntegerFielddjango.forms TypedChoiceFielddjango.http Http404django.http HttpResponsedjango.http HttpResponseBadRequestdjango.http HttpResponseForbiddendjango.http HttpResponseNotModifieddjango.http HttpResponsePermanentRedirectdjango.http HttpResponseRedirectdjango.template.response SimpleTemplateResponsedjango.template.response TemplateResponsedjango.urls.pathdjango.urls reverse_lazydjango.urls.exceptions NoReverseMatchdjango.urls.exceptions Resolver404django.utils.html format_htmldjango.utils.timezone ...or view the full table of contents.

Full Stack Python

Full Stack Python is an open book that explains concepts in plain language and provides helpful resources for those topics.
Updates via Twitter & Facebook.

Matt Makai 2012-2020