Display timestamp in django template

前端 未结 5 1093
太阳男子
太阳男子 2020-12-16 13:26

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

\"timestamp\":1337453263939 in milli seconds

I

5条回答
  •  伪装坚强ぢ
    2020-12-16 14:03

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

提交回复
热议问题