How can I convert integer unix timestamp to human readable format in django template?

I store the date as an integer field in my database and call it a timestamp. When I show it in a template, I tried to use it {{ timestamp | date:"D d M Y" }}, however it doesn’t output anything to me.

Did I do something wrong?

Edit: Sorry for the typo, I set the date: instead of date = in my code. However, since the timestamp was an integer field, should I convert it to datetime before doing this? Can I do this in the template itself? Since this line of code is in the middle of an iteration of the object array in the template.

+5
source share
3 answers
{{ timestamp|date:"D d M Y" }}

"="! = ":";)

EDIT:

, datetime, .

: {{ | : "D d M Y" }} datetime (, datetime.datetime.now()), string 'Wed 09 Jan 2008'.

: Django | -- |

, , ?

+3

templatetag. : , templatetags , __init__.py. templatetag timestamp_to_time.py. , , templatetag, INSTALLED_APPS.

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))

:

{{ value|timestamp_to_time|date:"jS N, Y" }} 

{# , format , #}

templatetag

{% load timestamp_to_time %}

+2

To work with the built-in Django date filter, you must use DateFieldor DateTimeField. Note that you can easily convert the timestamp to datetime python , which is the format used by DateField.

Also check the docs for the correct syntax :

{{ value|date:"D d M Y" }}
+1
source

All Articles