Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do i convert unix timestamp in integer to human readable format in django template?

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.

like image 510
Black Magic Avatar asked Jan 29 '12 19:01

Black Magic


2 Answers

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

like image 198
Peter Avatar answered Nov 19 '22 13:11

Peter


{{ 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?

like image 2
nana Avatar answered Nov 19 '22 12:11

nana