Jinja2 Extension for Dates and Times
npx @tessl/cli install tessl/pypi-jinja2-time@0.2.0A Jinja2 extension that adds time and date functionality to templates through a convenient now tag. It enables template developers to insert current timestamps with customizable formatting, timezone support, and time offset operations, making it ideal for generating dynamic content with time-sensitive information.
pip install jinja2-timefrom jinja2_time import TimeExtensionUsing with Jinja2 string-based extension loading:
from jinja2 import Environment
env = Environment(extensions=['jinja2_time.TimeExtension'])from jinja2 import Environment
from jinja2_time import TimeExtension
# Setup Jinja2 environment with the extension
env = Environment(extensions=[TimeExtension])
# Basic usage with default format (YYYY-MM-DD)
template = env.from_string("{% now 'utc' %}")
result = template.render() # e.g., "2023-12-09"
# Custom datetime format
template = env.from_string("{% now 'utc', '%a, %d %b %Y %H:%M:%S' %}")
result = template.render() # e.g., "Thu, 09 Dec 2023 15:30:45"
# Using local timezone
template = env.from_string("{% now 'local' %}")
result = template.render()
# Time offset operations
template = env.from_string("{% now 'utc' + 'hours=2, minutes=30' %}")
result = template.render() # Current time + 2.5 hours
template = env.from_string("{% now 'utc' - 'days=1, hours=6' %}")
result = template.render() # Yesterday, 6 hours earlier
# Configure default datetime format
env.datetime_format = '%Y-%m-%d %H:%M:%S'
template = env.from_string("{% now 'utc' %}")
result = template.render() # Uses custom default formatThe main extension class that integrates time functionality into Jinja2 templates.
class TimeExtension(jinja2.ext.Extension):
"""
Jinja2 extension for time and date functionality.
Attributes:
tags: Set of supported template tags (contains 'now')
"""
def __init__(self, environment):
"""
Initialize the TimeExtension.
Parameters:
- environment: jinja2.Environment instance
Effects:
- Adds datetime_format attribute to environment with default '%Y-%m-%d'
"""
def parse(self, parser):
"""
Parse the template tag syntax and return appropriate AST nodes.
Inherited from jinja2.ext.Extension. Processes {% now %} template tags
and determines whether to handle basic time display or offset operations.
Parameters:
- parser: jinja2.lexer.TokenStream parser instance
Returns:
- jinja2.nodes.Output node containing the processed time expression
"""The extension provides the {% now %} template tag with multiple syntax patterns for different use cases.
{% now 'timezone' %}
{% now 'timezone', 'format' %}Parameters:
timezone: Timezone specification
'utc' - UTC timezone'local' - Local system timezone'Europe/Berlin', 'America/New_York')format: Python strftime format string (optional)
environment.datetime_format (default: '%Y-%m-%d'){% now 'timezone' + 'offset_params' %}
{% now 'timezone' - 'offset_params' %}
{% now 'timezone' ± 'offset_params', 'format' %}Parameters:
offset_params: Comma-separated time offset parameters in interval=value format
years=N, months=N, weeks=N, days=Nhours=N, minutes=N, seconds=N, microseconds=N'hours=2', 'days=1, hours=3, minutes=30''hours=2.5', 'days=1.25'interval=value, separated by commas with optional spaces# Environment attribute added by TimeExtension
environment.datetime_format: strUsage:
env.datetime_format = '%a, %d %b %Y %H:%M:%S' # Set custom default formatDefault Value: '%Y-%m-%d'
Purpose: Used as fallback format when no explicit format is provided in the {% now %} tag.
__version__: str = '0.2.0'
__author__: str = 'Raphael Pierzina'
__email__: str = 'raphael@hackebrot.de'
__all__: List[str] = ['TimeExtension']class TimeExtension(jinja2.ext.Extension):
"""
Inherits from jinja2.ext.Extension base class.
Key inherited methods:
- parse(self, parser): Processes template tag syntax
- call_method(self, name, args, lineno): Calls extension methods from templates
"""
tags: Set[str] = {'now'} # Supported template tagsSupported timezone formats:
'utc' - Coordinated Universal Time'local' - Local system timezone'Europe/London', 'America/New_York', 'Asia/Tokyo'Supports Python's strftime() format codes:
Common format codes:
%Y - Year with century (e.g., 2023)%m - Month as zero-padded decimal (01-12)%d - Day as zero-padded decimal (01-31)%H - Hour as zero-padded decimal (00-23)%M - Minute as zero-padded decimal (00-59)%S - Second as zero-padded decimal (00-59)%a - Abbreviated weekday name (Mon, Tue, etc.)%A - Full weekday name (Monday, Tuesday, etc.)%b - Abbreviated month name (Jan, Feb, etc.)%B - Full month name (January, February, etc.)%Z - Timezone name%z - UTC offset (+0000, -0500, etc.)jinja2.exceptions.TemplateSyntaxErrorRaised when:
{% now %} (timezone is required)Invalid timezone names:
Invalid format strings:
strftime() may raise ValueError for invalid format codesInvalid offset parameters:
{% now %} tag evaluation performs a system time call