我有一个 API 在我的模板之一中填充一些数据。日期的输出为"2019-08-30T08:22:32.245-0700"
如何让日期读起来像 DD/MM/YY
我尝试过一些模板date:
输入内容,类似于使用 Jekyll 所做的事情,但没有任何效果
这就是我从 API 响应中显示它的方式。
<td class="text-center">{{ ticket.fields.updated }}</td>
我尝试过类似的方法:
<td class="text-center">{{ ticket.fields.updated | date: "Y,D,M " }}</td>
尝试:
class PostDetailView(DetailView):
'''
This view will hold infomation from Pendo / Salesforce and Jira
using their APIs to display the infomation.
'''
model = Post
template_name = 'clients/post_detail.html'
def render_to_response(self, context, **response_kwargs):
# pendo api
pendo_result = api_calls.pendo_data()
context['pendo_data'] = pendo_result
# jira api
jira_result = api_calls.jira_data()
context['jira_data'] = jira_result['issues']
return super().render_to_response(context, **response_kwargs)
@register.filter(expects_localtime=True, is_safe=False)
def date(value, arg=None):
jira_api = api_calls.jira_data()
jira_date = jira_api['fields']['updated']
if value in (None, ''):
return ''
if isinstance(value, str):
api_date_format = jira_date
value = datetime.datetime.strptime(value, api_date_format)
try:
return formats.date_format(value, arg)
except AttributeError:
try:
return format(value, arg)
except AttributeError:
return ''
最佳答案
如果从外部 API 检索,您的数据可能是字符串,而不是 Python datetime.date
对象。
在这种情况下,您的选择可能是:
- 自定义模板过滤器,将字符串转换为日期并将其格式化为所需格式的字符串
- 在您的 View 中将字符串转换为日期并将其格式化为具有所需格式的字符串
如果你想要 custom template filter ,我首先从 built-in date
filter 复制源代码并添加几行以从字符串转换为日期时间,然后将这些日期时间转换回新格式的字符串。
也许像这样,在名为 your_app/templatetags/custom_tags.py 的文件中:
from django import template
from django.utils import formats
register = template.Library()
@register.filter(expects_localtime=True, is_safe=False)
def custom_date(value, arg=None):
if value in (None, ''):
return ''
if isinstance(value, str):
api_date_format = '%Y-%m-%dT%H:%M:%S'
value = datetime.datetime.strptime(value, api_date_format)
try:
return formats.date_format(value, arg)
except AttributeError:
try:
return format(value, arg)
except AttributeError:
return ''
然后在您的模板中使用,如下所示:
{% load custom_tags %}
<td class="text-center">
{{ ticket.fields.updated|custom_date:"Y,D,M" }}
</td>
关于python-3.x - 如何从 Django 模板中的 API 响应转换日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57759653/