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 stringDescription
%aLocale’s abbreviated weekday name.
%ALocale’s full weekday name.
%bLocale’s abbreviated month name.
%BLocale’s full month name.
%cLocale’s appropriate date and time representation.
%dDay of the month as a decimal number [01,31].
%HHour (24-hour clock) as a decimal number [00,23].
%IHour (12-hour clock) as a decimal number [01,12].
%jDay of the year as a decimal number [001,366].
%mMonth as a decimal number [01,12].
%MMinute as a decimal number [00,59].
%pLocale’s equivalent of either AM or PM.
%SSecond as a decimal number [00,61].
%UWeek 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.
%wWeekday as a decimal number [0(Sunday),6].
%WWeek 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.
%xLocale’s appropriate date representation.
%XLocale’s appropriate time representation.
%yYear without century as a decimal number [00,99].
%YYear with century as a decimal number.
%ZTime 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_literalsfrom django.shortcuts import render# Import Datetimefrom datetime import datetimedef 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_literalsfrom django.shortcuts import render# Import Datetime classfrom datetime import datetimedef 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' }}
		
		
	
  • 19