在django模板中显示时间戳

fun*_*guy 15 django templates timestamp date

我需要在django模板中显示帖子的时间戳.时间戳如下:

"timestamp":1337453263939 in milli seconds
Run Code Online (Sandbox Code Playgroud)

我可以将时间戳转换为datetime对象并在视图中呈现它.是否有通过模板显示的直接方式?输出应该是:

print(datetime.datetime.fromtimestamp(1337453263.939))
2012-05-20 00:17:43.939000
Run Code Online (Sandbox Code Playgroud)

frn*_*nhr 75

{% now "U" %}
Run Code Online (Sandbox Code Playgroud)

"U"是Unix纪元的日期格式,也可以与内置date过滤器一起使用.所以,如果你在变量中有日期:

{{ value|date:"U" }}
Run Code Online (Sandbox Code Playgroud)

  • 这回答了一个不同的问题.OP要求_how将时间戳呈现为日期/时间string_,而不是_how将datetime对象呈现为timestamp_. (5认同)

sta*_*alk 27

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

  1. 在带有视图的应用程序中创建目录"templatetags",即呈现模板.
  2. 使用代码放入此目录空白文件"__init__.py"和"timetags.py":

    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)
    
    Run Code Online (Sandbox Code Playgroud)
  3. 在您的模板中,添加

    {% load timetags %}
    
    Run Code Online (Sandbox Code Playgroud)
  4. 在模板中使用以下语法:

    {{ timestamp|print_timestamp }}
    
    Run Code Online (Sandbox Code Playgroud)

    您的示例中的timestamp = 1337453263.939

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

import time
def print_timestamp(timestamp):
    ...
    #specify format here
    return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(ts))
Run Code Online (Sandbox Code Playgroud)

  • @tgdn这回答了OP的问题,frnhr的答案没有.(我解决了反问题.) (3认同)