What is the method to get current date time value in jinja
tags ?
On my project I need to show current time in UTC at top right corner of site.
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.now(datetime.UTC)
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
.