Jinja2 Time Extension
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
- breaking The `jinja2-time` library has not been updated since its 0.2.0 release in June 2016. It may have compatibility issues with newer major versions of Jinja2 (e.g., Jinja2 3.x), which introduced breaking changes such as the deprecation of `jinja2.Markup`.
- gotcha Timezone handling can be tricky. The `{% now %}` tag defaults to the server's local timezone if no timezone is explicitly provided. For predictable and consistent results, always specify a timezone like `'utc'` or a valid IANA timezone string (e.g., `'Europe/Berlin'`).
- gotcha The relative time offset syntax uses a specific string format (e.g., `'hours=2,seconds=30'`). Incorrectly formatted strings will lead to parsing errors or the offset being ignored. Ensure the key-value pair syntax is followed precisely.
- gotcha The format string for the `now` tag relies on Python's `strftime` codes. If you're unfamiliar with these codes, formatting may not yield the expected output. There are many subtle differences from other formatting languages.
Install
-
pip install jinja2-time
Imports
- TimeExtension
from jinja2_time import TimeExtension
Quickstart
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()}")