charliesneath
charliesneath

Reputation: 2039

Django date filter not showing formatted timestamp in rendered template

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?

Upvotes: 2

Views: 2473

Answers (1)

krs
krs

Reputation: 4154

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..." }}

Upvotes: 5

Related Questions