如何获取jinja的当前时间

How to get current time in jinja

jinja 标签中获取当前日期时间值的方法是什么?

在我的项目中,我需要在网站的右上角以 UTC 显示当前时间。

您应该使用 Python 的 datetime 库,获取时间并将其作为变量传递给模板:

>>> import datetime
>>> datetime.datetime.utcnow()
'2015-05-15 05:22:17.953439'

我喜欢@Assem 的。我将在 Jinja2 模板中对其进行演示。

#!/bin/env python3
import datetime
from jinja2 import Template

template = Template("""
# Generation started on {{ now() }}
... this is the rest of my template...
# Completed generation.
""")

template.globals['now'] = datetime.datetime.utcnow

print(template.render())

输出:

# Generation started on 2017-11-14 15:48:06.507123
... this is the rest of my template...
# Completed generation.

注:

我拒绝了某人的编辑,他说“datetime.datetime.utcnow() 是一种方法,而不是 属性”。虽然他们是“正确的”,但他们误解了不包括 () 的意图。包含 () 会导致在定义对象 template.globals['now'] 时调用该方法。这将导致模板中每次使用 now 都呈现相同的值,而不是从 datetime.datetime.utcnow.

获取当前结果

对于任何想要将 now 标签永久添加回 Jinja2 的人来说,这里有一个很好的示例来说明如何将其添加为 Jinja 扩展: https://www.webforefront.com/django/useandcreatejinjaextensions.html

这需要在 Django 网络应用的 python 脚本中定义一个新的 Jinja 扩展,然后将其作为扩展导入 settings.py

your_web_app/some_file.py中(我放在settings.py同一个目录下):

from jinja2 import lexer, nodes
from jinja2.ext import Extension
from django.utils import timezone
from django.template.defaultfilters import date
from django.conf import settings
from datetime import datetime


class DjangoNow(Extension):
    tags = set(['now'])

    def _now(self, date_format):
        tzinfo = timezone.get_current_timezone() if settings.USE_TZ else None
        formatted = date(datetime.now(tz=tzinfo),date_format)
        return formatted

    def parse(self, parser):
        lineno = next(parser.stream).lineno
        token = parser.stream.expect(lexer.TOKEN_STRING)
        date_format = nodes.Const(token.value)
        call = self.call_method('_now', [date_format], lineno=lineno)
        token = parser.stream.current
        if token.test('name:as'):
            next(parser.stream)
            as_var = parser.stream.expect(lexer.TOKEN_NAME)
            as_var = nodes.Name(as_var.value, 'store', lineno=as_var.lineno)
            return nodes.Assign(as_var, call, lineno=lineno)
        else:
            return nodes.Output([call], lineno=lineno)

然后,在 settings.py 中,将 DjangoNow class 添加到 OPTIONS 下的 extensions 列表中 TEMPLATES:

TEMPLATES = [
    ...
    { 
        'BACKEND':'django.template.backends.jinja2.Jinja2',
        ...
        'OPTIONS': { 
            ...,
            'extensions': [
                'your-app-name.some-file.DjangoNow',
                ],
        }       
   }
]

然后你就可以像在 Django 中一样使用 now 标签了,例如:

{% now 'U' %}

要将当前日期戳添加到使用 Jinja2 从 HTML 模板生成的 HTML 文档中:

#In the HTML template do:
{{ date.strftime('%B %d, %Y') }} <!-- Output format "Month DD, YYYY" -->

(最低)Python 代码:

## Tested in Python 3.6.8
import os
import datetime
import jinja2 

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)

#When building the values to pass to jinja
self.datapool=dict()
self.datapool['date']= datetime.datetime.now()

template = JINJA_ENVIRONMENT.get_template('./templates/base-html-template.html')
report=template.render(self.datapool)

我遇到了同样的问题,但终于找到了jinja2-time:

from jinja2 import Environment

env = Environment(extensions=['jinja2_time.TimeExtension'])

# Timezone 'local', default format -> "2015-12-10"
template = env.from_string("{% now 'local' %}")

# Timezone 'utc', explicit format -> "Thu, 10 Dec 2015 15:49:01"
template = env.from_string("{% now 'utc', '%a, %d %b %Y %H:%M:%S' %}")

# Timezone 'Europe/Berlin', explicit format -> "CET +0100"
template = env.from_string("{% now 'Europe/Berlin', '%Z %z' %}")

# Timezone 'utc', explicit format -> "2015"
template = env.from_string("{% now 'utc', '%Y' %}")

template.render()

关于 jinja2-time 扩展安装的更多信息:

jinja2-time is available for download from PyPI via pip:

$ pip install jinja2-time

It will automatically install jinja2 along with arrow.