7

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.

Did I do anything wrong?

Edit: 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.

Black Magic
  • 79
  • 1
  • 4

3 Answers3

4

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

{# replace value with the timestamp value and then format the time as you want #}

Be sure to have loaded the templatetag filter in the template with

{% load timestamp_to_time %}

before trying to use the filter

Peter
  • 6,509
  • 4
  • 30
  • 34
2
{{ timestamp|date:"D d M Y" }}

"=" != ":" ;)

EDIT:

If you have access to the view I would suggest sending the date to the template as a datetime object, not an integer.

From documentation: {{ value|date:"D d M Y" }} If value is a datetime object (e.g., the result of datetime.datetime.now()), the output will be the string 'Wed 09 Jan 2008'.

Here's a link to date function documentation: Django|Built-in-template-tags-and-filters|Date

Have you also tried printing out just the integer to see if there actually is the correct value in it?

nana
  • 4,426
  • 1
  • 34
  • 48
1

To work with Django's builtin date filter you should use a DateField or DateTimeField. Note that you can easily convert a timestamp to python datetime, which is the format used by the DateField.

Also check the docs for the correct syntax:

{{ value|date:"D d M Y" }}
Community
  • 1
  • 1
arie
  • 18,737
  • 5
  • 70
  • 76
  • 1
    The raw timestamp is an integer field. For the above example, if i just output the timestamp, it prints "1327871672". – Black Magic Jan 29 '12 at 21:18
  • Then you should either convert the timestamp field to a datetime field so you can use the builtin date filter or you should write your own filter/tag that formats unix timestamps. – arie Jan 29 '12 at 21:58