在 Django 模板中显示时间戳 [英] Display timestamp in django template

查看:21
本文介绍了在 Django 模板中显示时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 django 模板中显示帖子的时间戳.时间戳是这样的:

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

推荐答案

您可以使用自定义模板过滤器(参见 https://docs.djangoproject.com/en/dev/howto/custom-template-tags/).在你的情况下,它可能是这样的:

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. 在具有视图的应用程序中创建目录templatetags",用于呈现模板.
  2. 将空白文件__init__.py"和timetags.py"放入此目录,代码如下:

  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)

  • 在您的模板中,添加

  • In your template, add

    {% load timetags %}
    

  • 在模板中使用以下语法:

  • Use following syntax in template:

    {{ timestamp|print_timestamp }}
    

    您的示例中的时间戳 = 1337453263.939

    Where timestamp = 1337453263.939 from your example

    这将以本地日期和时间格式打印时间戳.如果要自定义输出,您可以通过以下方式修改 print_timestamp:

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

    这篇关于在 Django 模板中显示时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆