Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display timestamp in django template

Tags:

I need to display timestamp of a post with in django template. The timestamp would be like:

"timestamp":1337453263939 in milli seconds

I can convert the timestamp into datetime object and render it in the view. Is there is any direct way to display through the template? The output should be:

print(datetime.datetime.fromtimestamp(1337453263.939))
2012-05-20 00:17:43.939000
like image 764
funnyguy Avatar asked May 23 '12 07:05

funnyguy


2 Answers

{% now "U" %}

The "U" is a date format for Unix epoch, and can also be used with built-in date filter. So, if you have the date in a variable:

{{ value|date:"U" }}
like image 169
frnhr Avatar answered Oct 02 '22 22:10

frnhr


You could use custom template filters (see https://docs.djangoproject.com/en/dev/howto/custom-template-tags/). In your case it could like this:

  1. Create directory 'templatetags' in application with view, that renders template.
  2. Put into this dir blank file "__init__.py" and "timetags.py" with code:

    from django import template
    import datetime
    register = template.Library()
    
    def print_timestamp(timestamp):
        try:
            #assume, that timestamp is given in seconds with decimal point
            ts = float(timestamp)
        except ValueError:
            return None
        return datetime.datetime.fromtimestamp(ts)
    
    register.filter(print_timestamp)
    
  3. In your template, add

    {% load timetags %}
    
  4. Use following syntax in template:

    {{ timestamp|print_timestamp }}
    

    Where timestamp = 1337453263.939 from your example

This will print timestamp in local date and time format. If you want to customize output, you can modify print_timestamp in following way:

import time
def print_timestamp(timestamp):
    ...
    #specify format here
    return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(ts))
like image 44
stalk Avatar answered Oct 02 '22 20:10

stalk