How to get current time in jinja

I faced the same problem, but finally found 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()

More about jinja2-time extension installation:

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

$ pip install jinja2-time

It will automatically install jinja2 along with arrow.


You should use datetime library of Python, get the time and pass it as a variable to the template:

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

I like @Assem's answer. I'm going to demo it in a Jinja2 template.

#!/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())

Output:

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

Note:

I rejected an edit from someone who stated "datetime.datetime.utcnow() is a method, not a property". While they are "correct", they misunderstood the intention of NOT including the (). Including () causes the method to be called at the time the object template.globals['now'] is defined. That would cause every use of now in your template to render the same value rather than getting a current result from datetime.datetime.utcnow.

Tags:

Jinja2