Django date filter not showing formatted timestamp in rendered template

感情迁移 提交于 2019-12-11 02:43:48

问题


I'm trying to format a timestamp into a date using Django's {{ timestamp|date:"d M Y" }} feature.

I'm running into a problem where I can output and see the raw timestamp with {{ timestamp }}, but the formatting via filter isn't outputting anything when my page is rendered using {{ timestamp|date:"d M Y" }}.

For example, right now the result of {{ timestamp }} - {{ timestamp|date:"d M Y" }} is 1317945600 - when I load the page.

Any suggestions on what I might be doing wrong?


回答1:


The problem is that date doesnt want a timestamp, it wants a datetime or date object. you have to parse the timestamp in python or make a templatetag.

add this to templatetags/mytags.py

from datetime import datetime
from django import template
register = template.Library()

@register.filter("timestamp")
def timestamp(value):
    try:
        return datetime.fromtimestamp(value)
    except AttributeError:
        return ''

Then use it with

{{ some_timestamp_value|timestamp|date:"format..." }}


来源:https://stackoverflow.com/questions/7698542/django-date-filter-not-showing-formatted-timestamp-in-rendered-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!