Jinja2 Time Extension

0.2.0 · maintenance · verified Sun Apr 12

Jinja2-time is a Jinja2 extension that provides a `now` tag for convenient access to date and time functionalities directly within Jinja2 templates. It allows retrieving the current time in various timezones, formatting it using Python's `strftime` patterns, and applying relative time offsets. The current version is 0.2.0, released in June 2016. It relies on Jinja2 and `arrow` for robust date and time handling.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a Jinja2 environment with `jinja2-time` and use the `now` tag to display the current time in various timezones, with custom formatting, and with relative time offsets. It also shows how to set a default datetime format for the environment.

from jinja2 import Environment

# Configure Jinja2 environment with the TimeExtension
env = Environment(extensions=['jinja2_time.TimeExtension'])

# Example 1: Get current UTC time with default format
template_utc_default = env.from_string("{% now 'utc' %}")
print(f"UTC (default format): {template_utc_default.render()}")

# Example 2: Get current UTC time with explicit strftime format
template_utc_formatted = env.from_string("{% now 'utc', '%a, %d %b %Y %H:%M:%S' %}")
print(f"UTC (formatted): {template_utc_formatted.render()}")

# Example 3: Get local time with a relative offset (add 2 hours, 30 seconds)
template_offset = env.from_string("{% now 'local' + 'hours=2,seconds=30' %}")
print(f"Local (+2h30s): {template_offset.render()}")

# Example 4: Set a default datetime format for the environment
env.datetime_format = '%Y-%m-%d %H:%M:%S %Z'
template_local_default_env = env.from_string("{% now 'local' %}")
print(f"Local (env default format): {template_local_default_env.render()}")

view raw JSON →