Python Django format date

In this Python Django Tutorial, we will understand the Python Django format date. And we will also discuss examples related to format date in Django. Here is the list of topics that we are going to cover.

  • How to get date in Python django
  • Python django format date
  • Python django format date in view
  • Python django format date dd/mm/yyyy
  • Python django format date in template
  • Python django format date locale

How to get date

Before we can format a date, we must either get the current Date value or specify the date we want to format.

The simplest approach to define or retrieve the date in Django is to use python’s DateTime module. This datetime module contains many different classes that can be used to manipulate date values.

To generate or fetch dates, we use the date class. And, to get or set the date, you can use any one of the following functions.

  • datetime.date(): This function is used to set specific date. It takes three arguments: year, month and day.
  • datetime.date.today(): This function is used to get today’s date.

Also, check: How to Get Current time in Django

Python django format date

Since the way dates are expressed in different places may differ, we may need to format the date at times. We have two methods for formatting dates in Python, which we can easily use in Django.

The following are the functions:

  • strftime(): This function generates a formatted string from a date object. It accepts one or more formatted code as input and outputs a string representation.
  • strptime(): This method is used to format a string-formatted date. It requires two inputs, the first of which is of which is a date string and the second of which is a formatted code.

The most popular Django date filters for formatting dates are listed below.

Format CharacterDescriptionExample
%aAbbreviated day name.Fri, Sun
%AFull name of the day.Friday, Sunday
%BFull name of the month.June, July
%bAbbreviated month name.Jan, Feb
%mMonth as a zero-padded decimal number.06, 10
%dDay of the month as a zero-padded decimal.18, 31
%yThe year without century as a zero-padded decimal number.99, 22
%YThe year with century as a decimal number.1999, 2022
%jDay of the year as a zero-padded decimal number.135, 365
%UWeek number of the year. The first day as Sunday.28, 53
%WWeek number of the year. The first day as Monday.00, 53
%xLocale’s appropriate date representation.12/31/18
Date Format Characters

Read: Python Django vs Flask – Key Differences

Python django format date in view

In this section, we’ll learn how to format dates using a view file in Django. The views.py file will be used to get the date and then format it.

We’ll go over a bunch of examples to help clarify our concept.

Before I begin the example, I’ll show you the project’s urls.py file.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('home/', include('home.urls'))
]

This means that when you open your project in the browser and type “home/ “ in the URL, it will take you to your home.urls.

Now, see the home’s urls.py file:

from django.contrib import admin
from django.urls import path, include
from home import views

urlpatterns = [
    path('', views.home, name='home')
]

It moves to the views.py file of the home app.

Example #1

In this example, we format the day of the month as a zero-padded decimal, the month as an abbreviated name, and the year without century as a zero-padded decimal number.

Now, see the views.py file:

# Import Libraries

from django.shortcuts import render
import datetime

# Create your views here.

def home(request):
    currentdate = datetime.date.today()
    formatDate = currentdate.strftime("%d-%b-%y")
    return render(request,'home.html',
                  {'current_date':currentdate,
                   'format_date':formatDate} )    

In the views.py file, we have created a simple view that fetches the Current Date value and Formatted Date value into a variable. And it also returns the variable to the home.html page.

Now, see the home.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PythonGuides</title>
</head>
<body>
    <p>
        <b>Current Date : </b>{{current_date}}
        <br>
        <br>
        <b>Formatted Date : </b>{{format_date}}
    </p>
</body>
</html>

In the home.html file, we are just using the variable to get the Current date value and Formatted date value. In the end, we will get the following output.

python django format date in view
Format Date

Read Compare two integers in Python Django

Example #2

In this example, we acquire the current date and print the abbreviated day name.

The urls.py file in the project and the urls.py file in the home are the same as in the previous example.

Now, see the views.py file:

from django.shortcuts import render
import datetime

# Create your views here.

def home(request):
    currentdate = datetime.date.today()
    formatDate = currentdate.strftime("%a")
    return render(request,'home.html',                 
                  {'current_date':currentdate,
                   'format_date':formatDate} )    

We constructed a simple view in the views.py file that retrieves the Current Date value and the Formatted Date value into variables. The variable is also returned to the home.html page.

Now, see the home.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PythonGuides</title>
</head>
<body>
    <p>
        <b>Current Date : </b>{{current_date}}
        <br>
        <br>
        <b>Abbreviated Day Name: </b>{{format_date}}
    </p>
</body>
</html>

We just use the variable to acquire the current date value and the abbreviated day name in the home.html file. Finally, we’ll receive the following result.

python django format date in views
Format Date

From here, we clearly know that on 7 Feb 2022, the day is Mon.

Example #3

In this example, we get the current date and output the day of the year as a zero-padded decimal number.

The views.py file:

from django.shortcuts import render
import datetime

# Create your views here.

def home(request):
    currentdate = datetime.date.today()
    formatDate = currentdate.strftime("%j")
    return render(request,'home.html',{'current_date': 
                  currentdate,'format_date':formatDate} )    

The home.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PythonGuides</title>
</head>
<body>
    <p>
        <b>Current Date : </b>{{current_date}}
        <br>
        <br>
        <b>Day of the Year: </b>{{format_date}}
    </p>
</body>
</html>
fromate date in views django python
Format Date

The year 2022 has 365 days, with February 7th being the 38th day of the year.

Read Outputting Python to html Django

Example #4

In this example, we obtain the current date and the output is the year’s week number if the first day is Monday.

The views.py file:

from django.shortcuts import render
import datetime

# Create your views here.

def home(request):
    currentdate = datetime.date.today()
    formatDate = currentdate.strftime("%W")
    return render(request,'home.html',{'current_date': 
                  currentdate,'format_date':formatDate} )    

The home.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PythonGuides</title>
</head>
<body>
    <p>
        <b>Current Date : </b>{{current_date}}
        <br>
        <br>
        <b>Week number of the Year: </b>{{format_date}}
    </p> 
</body>
</html>
formate date in django using views
Format Date

The year 2022 has 365 days, with the week number of the year. The output is as fellow:

Example #5

In this example, we get the next date and format its month as a zero-padded decimal number.

The views.py file:

from django.shortcuts import render
import datetime

# Create your views here.

def home(request):
    currentdate = datetime.date(2022, 2, 28) + 
                  datetime.timedelta(days=1)
    formatDate = currentdate.strftime("%m")
    return render(request,'home.html',{'current_date': 
                  currentdate,'format_date':formatDate} )    

Simply use the + symbol to acquire future dates, and then use datetime to determine the number of days you want. The function timedelta() is used to calculate the date difference between two points.

The home.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PythonGuides</title>
</head>
<body>
    <p>
        <b>Current Date : </b>{{current_date}}
        <br>
        <br>
        <b>Month as Number: </b>{{format_date}}
    </p> 
</body>
</html>
format date in views using python django
Format Date

The output shows March is the third month of the year.

Read: Python Django get admin password

Python django format date dd/mm/yyyy

In this section, we’ll learn how to use Python Django to format dates in a certain manner. And, because the format is dd/mm/yyyy, we must use a slash to separate the date, month and year.

To separate the day from the month and the month from the year in a date notation we use DateSeparator. The following list will show the valid date separators.

SeparatorDescription
/Slash
Dash
.Period
,Comma
Black
Date Separator

You can use any one of them as per your choice.

Example #1

The same project’s urls.py and home’s urls.py files will be used as in the previous topic.

Now, let’s see the views.py file:

from django.shortcuts import render
import datetime

# Create your views here.

def home(request):
    currentdate = datetime.date(1869, 10, 2)
    formatDate = currentdate.strftime("%d/%B/%Y")
    return render(request,'home.html',{'current_date': 
                  currentdate,'format_date':formatDate} )    

We format the date to day of the month as a zero-padded decimal, the full name of the month as a decimal number, and the year with century as a decimal number using a slash separator.

Now let’s see the home.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PythonGuides</title>
</head>
<body>
    <p>
        <b>Current Date : </b>{{current_date}}
        <br>
        <br>
        <b>Format Date: </b>{{format_date}}
    </p> 
</body>
</html>
python django format date ddmmyyy
Python Django format date dd/mm/yyyy

Example #2

In this example, we format the date to day of the month as a zero-padded decimal, month as a zero-padded decimal number, and year with century as a decimal number and separate them using slash separator.

The views.py file:

from django.shortcuts import render
import datetime

# Create your views here.

def home(request):
    currentdate = datetime.date.today() + 
                  datetime.timedelta(days=5)
    formatDate = currentdate.strftime("%m/%d/%Y")
    return render(request,'home.html',{'current_date': 
                  currentdate,'format_date':formatDate} )    

Here we use the datetime.timedelta function with days equal to 5 to get the next 5-day date.

The home.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PythonGuides</title>
</head>
<body>
    <p>
        <b>Current Date : </b>{{current_date}}
        <br>
        <br>
        <b>Format Date: </b>{{format_date}}
    </p> 
</body>
</html>
python django format date ddmmyyyy using slash separator
dd/mm/yyyy

We have an example with a dash separator in the previous topic, you can see it.

Read: How to Create model in Django

Python django format date in template

In this section, we’ll learn to format date in python Django using built-in Django templates.

We’ve only discussed formatting the current date in the views.py file and sent it to the template page so far. Now we’ll see how to use Django template tags to format the current date.

The following are the most common format strings available in Django.

Format CharacterDescriptionExample
dDay of the month, with 2 digits leading zeros.02, 28
jDay of the month without leading zeros.2, 28
DAbbreviated day of the week, in textual format.Sat, Sun
lFull name day of the week, in textual format.Saturday, Sunday
SEnglish ordinal suffix for the day of the month, 2 characters.‘st’, ‘nd’, ‘rd’ or ‘th’
wDay of the week, digits without leading zeros.0 for Sunday, 6 for Saturday
zDay of the year.1, 212, 365
mThe month, with 2 digits leading zeros.01 – 12
nThe month without leading zeros.1 – 12
MThe abbreviated month of the year, in textual format.Jan, Feb
bThe abbreviated month of the year, in textual format, lowercase.jan, feb
FFull name of the month in the year, in textual format.January
yYear, 2 digits with leading zeros.00 – 99
YYear, 4 digits with leading zeros.1999, 2002
Format Character in Django

Example #1

Firstly, we will create a view that will redirect to an HTML page. In the view.py file, we define the date using the date() method and redirect the date value to the home.html page.

The code of the views.py file is as follows:

from django.shortcuts import render
import datetime 

# Create your views here.

x = datetime.date(2002, 6, 5)

def home(request):
    return render(request,'home.html', {'my_date' : x})    

Next, we will add the “date” tag to the home.html file to get the result. Also, we can have the current date in different formats using this tag.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PythonGuides</title>
</head>
<body>
    <p>
        <b> Environment Day : </b> {{my_date|date:"jS M Y"}}
        <br>
        <b> Environment Day : </b> {{my_date|date:"l,d F y"}}
        
    </p> 
</body>
</html>

Now, start the server and open the mapped URL in the browser. We will get the following result.

python django format date in template
Format Date In Template

Example #2

The code of the views.py file is as follows:

from django.shortcuts import render
import datetime 

# Create your views here.

x = datetime.date(2002, 1, 24)

def home(request):
    return render(request,'home.html', {'my_date' : x})    

The code of the home.html file is as fellow:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PythonGuides</title>
</head>
<body>
    <p>
        <b> Delivery Date: </b> {{my_date|date:"j-n-Y"}}
        <br>
        <b> Delivery Day : </b> {{my_date|date:"D"}}
        
    </p> 
</body>
</html>
formate date in template using python django
Format Date In Template

Example #3

In this example, we print the day of the week in letters and digits both and also a day of the year.

The views.py file:

from django.shortcuts import render
import datetime 

# Create your views here.

x = datetime.date.today()

def home(request):
    return render(request,'home.html', {'my_date' : x})    

The home.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PythonGuides</title>
</head>
<body>
    <p>
        <b> Day of the Week : </b> {{my_date|date:"l"}}
        <br>
        <b> Day of the week (digits)  : </b> 
            {{my_date|date:"w"}}
        <br>
        <b> Day of the year  : </b> {{my_date|date:"z"}}
    </p> 
</body>
</html>

The output is as fellow:

python django format date in template filter
Format Date

Read: Django get all data from POST request

Python django format date locale

We may run across a few dates when constructing our Django application. But, you know, the way you’d expect them to be displayed might not be the same as how I’d expect them to be displayed, right? So, let’s see how we can prevent our client from mistaking a day for a month because we displayed the date in an unfamiliar manner on our app.

Django includes a sophisticated formatting mechanism for formatting internationalization-related units like dates, times, and numerals to their localized representations before displaying them on templates.

To turn on your formatting mechanism, open your project’s settings.py file and set the following setting:

USE_L10N = True

Dates were shown in Django based on the browser language or the language code defined in your project. So, let’s see the different ways to change the language:

  • Using MIDDLEWARE
  • Using LANGUAGE_CODE

Using MIDDLEWARE

We can hand over the remote to our users instead of trying to figure out the language on our own.  This is accomplished with the help of the Django framework’s Middleware plugin.
Django includes a set of Middleware components by default.

And from that group of middleware, we may select the LocaleMiddleware as the best fit for our needs.LocaleMiddleware selects the localized language based on the request’s databases.

The following steps are used to set Local Middleware:

  1. Open the settings.py file in our project’s directory.
  2. Find MiddleWear List
  3. Add Local MiddleWear inside it.
'django.middleware.locale.LocaleMiddleware'

LocaleMiddleware should be placed after SessionMiddleware and before CommonMiddleware.

Let’s see examples to understand the concept more clearly:

The project’s urls.py file:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('home/', include('home.urls'))
]

This signifies that if you open your project in a browser and type “home/” into the URL, you’ll be directed to your home.urls file.

The app’s urls.py file:

from django.contrib import admin
from django.urls import path, include
from home import views

urlpatterns = [
    path('', views.home, name='home')
]

It then goes to the home app’s views.py file.

The views.py file:

from django.shortcuts import render
import datetime 

# Create your views here.

x = datetime.date.today()

def home(request):
    return render(request,'home.html', {'my_date' : x})   

We created a simple view in the views.py file that retrieves the Current Date and Formatted Date values into a variable. The variable is also returned to the home.html page.

The home.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PythonGuides</title>
</head>
<body>
    <p>
        <b> Format Date : </b> {{my_date}} 
        <br>
        <b> Format Date (Different Style): </b> {{my_date|date:"l,jS b 
                                                                Y"}} 
   </p>
</body>
</html>

We use the template filters in the home.html file to acquire the Formatted date value in several ways. Finally, we’ll receive the following result.

Example #1

Browser Language: English

python django format date locale
Locale Date

We may now go ahead and change our browser’s language. It will return a page with the localized settings we set earlier when we refresh.

Example #2

Browser Language: German

fomat date locale python django
Locale Date

Example #3

Browser Language: Portuguese (Brazil)

format date locale python using python django
Locale Date

Using LANGUAGE_CODE

Next, the way to change the language is using the LANGUAGE_CODE tag which we can set in a Django project’s settings file.

Let us open up the settings.py file in the project root and set its LANGUAGE_CODE value to supported HTML language:

LANGUAGE_CODE='<language id format>'

Django uses the LANGUAGE_CODE in the following cases:

  • If the project is set up to use LocaleMiddleware, but it is unable to detect the user’s chosen language for some reason, the LANGUAGE_CODE provides a fallback strategy by specifying the language to which it will revert.
  • If the project does not use LocaleMiddleware, the LANGUAGE_CODE is used to serve all clients as the default language.

Let’s see examples related to this:

Example #1

The Setting.py file:

LANGUAGE_CODE = 'en-us'

The same URLs file is used as in the MiddleWare Case.

The views.py file:

from django.shortcuts import render
import datetime 

# Create your views here.

x = datetime.date(2022, 1, 26)

def home(request):
    return render(request,'home.html', {'my_date' : x})   

The home.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PythonGuides</title>
</head>
<body>
    <p>
        <b> Format Date : </b> {{my_date}} 
    
   </p>
</body>
</html>

The output is as fellow:

format date locale using django
Format date locale using Django

Example #2

The Setting.py file:

LANGUAGE_CODE = 'it'

Then the output is as follow:

format locale date using django
Format locale date using Django

Example #3

The Setting.py file:

LANGUAGE_CODE = 'es'

Then the output is as follow:

python django format locale date
Python Django format locale date

Also, take a look at some more Django tutorials.

In this Python Django Tutorial, we discussed the Python Django format date. Also, we discuss the following list of topics.

  • How to get date
  • Python django format date
  • Python django format date in view
  • Python django format date dd/mm/yyyy
  • Python django format date in template
  • Python django format date locale