Ad
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
Ad
Answer
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
Ad
source: stackoverflow.com
Related Questions
- → Django, code inside <script> tag doesn't work in a template
- → Uncaught ReferenceError: Parent is not defined
- → React - Django webpack config with dynamic 'output'
- → Put a Rendered Django Template in Json along with some other items
- → Implement shopify templates in django
- → Python Shopify API output formatted datetime string in django template
- → How to avoid being crawled/penalized by Google
- → Django: Identify the urls that provide duplicate content and set a canonical link
- → Shopify app: adding a new shipping address via webhook
- → Jquery Modal Confirmation on Django form submit for deletion of object
- → changing the size of an image with css
- → shopify_auth multi store session handling
- → How to use Shopify Python API RecurringApplicationCharge
Ad