1

我从互联网上的 API 获取日期数据,但它以字符串形式出现。如何使用 django HTML 模板标签将其转换为以下格式?

当前日期数据格式:2022-02-13 00:00:00 UTC

我的愿望格式:2022年2月13日00:00

我希望另一种格式:2022 年 2 月 13 日

4

1 回答 1

2

因为在模板中使用 Python 并不是那么简单,所以我们需要创建自定义模板标签。让我们从在您的应用程序中创建文件夹开始,我们将其命名为 custom_tags.py。它应该在YourProject/your_app/templatetags/文件夹中创建,因此我们还必须在其中创建 templatetags 文件夹。

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 %}

如果您可以datetime直接获取对象,则可以date在模板中使用标签。

用法:

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

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

在Django DOCS中阅读更多内容

于 2022-02-13T17:58:19.077 回答