Django HTML Template Tag For Date

- 1 answer

I get date data from an API on the internet, but it comes as a string. How do I convert this to the following format using django HTML template tag?

Current date data format: 2022-02-13 00:00:00 UTC

My wish format: 13 February 2022 00:00

My wish another format: 13 February 2022



Because in templates it's not that simple to use Python, we need to create custom Template Tag. Let's start with creating folder in your app, let's name it It should be created in YourProject/your_app/templatetags/ folder, so we have to also create templatetags folder in there.

from django import template
import datetime

register = template.Library()

def format_date(date_string):
    return datetime.datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S %Z')


{% load custom_tags %}

{{ datetime_from_API|format_date|date:'d F Y j:i' }}

# or if that does not work - I can't check it right now

{% with datetime_from_API|format_date as my_date %}
    {{ my_date|date:'d F Y j:i' }}
{% endwith %}

If you can get datetime objects directly you can use date tag in templates.


with hour:
{{ some_model.datetime|date:'d F Y j:i' }}

date only:
{{ some_model.datetime|date:'d F Y' }}

Read more in Django DOCS