更新时间:2022-12-18 12:27:06
您需要创建一个自定义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 %}
尝试使用过滤器之前