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.
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
{{ timestamp|date:"D d M Y" }}
"=" != ":" ;)
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With