How to format datetime objects in the view and template in Django

Working with dates in Django? The datetime module of Python offers classes for manipulating dates and times easily. You can format any date of Python (as long as it is a datetime object) using the strftime method.

Date formatting

A datetime object will have the method strftime that allows you to provide a custom format to a date and print it as a string wherever you need to. You can specify how and where every part of the date should be rendered with the following identifiers:

Format string Description
%a Locale’s abbreviated weekday name.
%A Locale’s full weekday name.
%b Locale’s abbreviated month name.
%B Locale’s full month name.
%c Locale’s appropriate date and time representation.
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%I Hour (12-hour clock) as a decimal number [01,12].
%j Day of the year as a decimal number [001,366].
%m Month as a decimal number [01,12].
%M Minute as a decimal number [00,59].
%p Locale’s equivalent of either AM or PM.
%S Second as a decimal number [00,61].
%U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.
%w Weekday as a decimal number [0(Sunday),6].
%W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.
%x Locale’s appropriate date representation.
%X Locale’s appropriate time representation.
%y Year without century as a decimal number [00,99].
%Y Year with century as a decimal number.
%Z Time zone name (no characters if no time zone exists).
%% A literal '%' character.

In the View

Within the controller, you have access directly to the datetime object. That means that you can simply execute the strftime function an pass the format string as first argument:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render

# Import Datetime
from datetime import datetime

def index(request):
    # return HttpResponse("<h1>Hello, world !</h1>")
    # Some Date Object, for example a default generated by datetime
    myDate = datetime.now()
    
    # Give a format to the date
    # Displays something like: Aug. 27, 2017, 2:57 p.m.
    formatedDate = myDate.strftime("%Y-%m-%d %H:%M:%S")

    # Do something with the formatted date
    return render(request, 'pages/index.html', {
        'date': formatedDate
    })

In the Template

If you are willing to format the string in the template and not in the view (controller), you can do it with a filter namely date. The following View (controller) returns a date object to a simple template that will print the date sent from the view:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render

# Import Datetime class
from datetime import datetime

def index(request):

    # Some Date Object, for example a default generated by datetime
    myDate = datetime.now()

    # Render Some Template with a parameter accesible as date
    return render(request, 'pages/index.html', {
        'myDate': myDate
    })

The content of the following template (index.html) will use the following code to format the providen date object:

Prints something like:  Aug. 27, 2017, 2:57 p.m.
{{ myDate|date:'Y-m-d H:i' }}

Happy coding !

This could interest you

Become a more social person