问题
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