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 Code Examples django.urls.path django.conf.urls.url django.contrib.admin django.db.models Model django.dispatch Signal django.db.models.signal django.core.mail.send_mail django.core.mail.messages EmailMessage django.conf settings django.forms django.contrib.admin.sites register BaseCommand django.utils.timezone django.contrib.auth get_user_model django.contrib.auth.decorators login_required django.core.exceptions ImproperlyConfigured django.utils.html format_html django.contrib.auth.hashers make_password django.http Http404 django.http HttpResponse django.http HttpResponseForbidden django.http HttpResponseBadRequest django.contrib.admin.filters SimpleListFilter django.urls.exceptions NoReverseMatch django.http HttpResponsePermanentRedirect django.http HttpResponseNotModified django.http HttpResponseRedirect django.apps.config AppConfig django.db OperationalError flask_sqlalchemy.SQLAlchemy Model django.db.models CharField django.db.models TextField django.db.models BooleanField flask request flask redirect django.db.models DateTimeField django.db.models IntegerField django.db.models AutoField django.db.models DateField django.db.models FileField django.template.response TemplateResponse django.template.response SimpleTemplateResponse SQLAlchemy Model Examples django.urls reverse_lazy Flask Core and Extensions Code Examples ...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-2019