djangodjango-templatesdjango-tagging

Django HTML template tag for date


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


Solution

  • 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 custom_tags.py. It should be created in YourProject/your_app/templatetags/ folder, so we have to also create templatetags folder in there.

    custom_tags.py:

    from django import template
    import datetime
    
    register = template.Library()
    
    @register.filter(name='format_date')
    def format_date(date_string):
        return datetime.datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S %Z')
    

    your_template.html:

    {% 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.

    usage:

    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