问题描述
我将日期存储为数据库中的整数字段,并将其称为时间戳。当我在模板中显示它时,我尝试使用 {{timestamp | date: D d MY}}
,但是,这对我没有任何输出。
I store the date as integer field in my database and called it timestamp. When I display it in template, I tried to use {{ timestamp | date:"D d M Y" }}
, however, this does not output anything for me.
我做错了吗?
编辑:
抱歉,我确实输入了date:而不是date =在我的代码中。但是,由于时间戳记是整数字段,因此在执行此操作之前我应该将其转换为日期时间吗?我可以在模板本身中执行此操作吗?由于此行代码位于迭代模板中的对象数组的中间。
Sorry for the typo, I did put date: instead of date= in my code. However, since the timestamp was integer field, should I convert it to datetime before doing this? Can I do it in the template itself? Since this line of code is in the middle of iterating an array of object in the template.
推荐答案
您需要创建一个自定义templatetag过滤器。我为您制作了一个:只需确保您在 app目录中有一个 templatetags
文件夹,然后创建一个空文件 __ init __。py
在目录中。还将下面的代码另存为templatetag目录中的 timestamp_to_time.py
。
还请确保包含此templatetag目录的应用程序位于 INSTALLED_APPS
设置变量中。
You need to create a custom templatetag filter. I made this one for you: just make sure you have a templatetags
folder in the app directory and then create an empty file __init__.py
in the directory. Also save the code below in the templatetag directory as timestamp_to_time.py
.Also make sure that the app containing this templatetag directory is in the INSTALLED_APPS
settings variable.
from django import template
register = template.Library()
@register.filter('timestamp_to_time')
def convert_timestamp_to_time(timestamp):
import time
return datetime.date.fromtimestamp(int(timestamp))
然后您可以在模板中使用过滤器,如下所示:
In your template you can then use the filter as follow:
{{ value|timestamp_to_time|date:"jS N, Y" }}
{#用时间戳记值替换 value 然后格式化您想要的时间#}
{# replace value with the timestamp value and then format the time as you want #}
请确保已使用加载了模板中的templatetag过滤器p>
Be sure to have loaded the templatetag filter in the template with
{% load timestamp_to_time %}
尝试使用过滤器之前
这篇关于如何在Django模板中将整数形式的unix时间戳转换为人类可读的格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!