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)
sta*_*alk 27
您可以使用自定义模板过滤器(请参阅https://docs.djangoproject.com/en/dev/howto/custom-template-tags/).在你的情况下它可能是这样的:
使用代码放入此目录空白文件"__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)在您的模板中,添加
{% load timetags %}
Run Code Online (Sandbox Code Playgroud)在模板中使用以下语法:
{{ 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)
| 归档时间: |
|
| 查看次数: |
29564 次 |
| 最近记录: |