or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/pypi-jinja2-time

Jinja2 Extension for Dates and Times

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/jinja2-time@0.2.x

To install, run

npx @tessl/cli install tessl/pypi-jinja2-time@0.2.0

index.mddocs/

Jinja2-Time

A 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.

Package Information

  • Package Name: jinja2-time
  • Package Type: pypi
  • Language: Python
  • Installation: pip install jinja2-time
  • Dependencies: jinja2, arrow

Core Imports

from jinja2_time import TimeExtension

Using with Jinja2 string-based extension loading:

from jinja2 import Environment
env = Environment(extensions=['jinja2_time.TimeExtension'])

Basic Usage

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 format

Capabilities

Extension Class

The 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
        """

Template Tag Syntax

The extension provides the {% now %} template tag with multiple syntax patterns for different use cases.

Basic Time Display

{% now 'timezone' %}
{% now 'timezone', 'format' %}

Parameters:

  • timezone: Timezone specification
    • 'utc' - UTC timezone
    • 'local' - Local system timezone
    • IANA timezone names (e.g., 'Europe/Berlin', 'America/New_York')
  • format: Python strftime format string (optional)
    • If omitted, uses environment.datetime_format (default: '%Y-%m-%d')

Time Offset Operations

{% 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=N
    • hours=N, minutes=N, seconds=N, microseconds=N
    • Examples: 'hours=2', 'days=1, hours=3, minutes=30'
    • Supports fractional values: 'hours=2.5', 'days=1.25'
    • Format: Each parameter as interval=value, separated by commas with optional spaces

Environment Configuration

# Environment attribute added by TimeExtension
environment.datetime_format: str

Usage:

env.datetime_format = '%a, %d %b %Y %H:%M:%S'  # Set custom default format

Default Value: '%Y-%m-%d'

Purpose: Used as fallback format when no explicit format is provided in the {% now %} tag.

Package Metadata

__version__: str = '0.2.0'
__author__: str = 'Raphael Pierzina'  
__email__: str = 'raphael@hackebrot.de'
__all__: List[str] = ['TimeExtension']

Types

Extension Inheritance

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 tags

Timezone Support

Supported timezone formats:

  • 'utc' - Coordinated Universal Time
  • 'local' - Local system timezone
  • IANA timezone names (full list depends on system configuration)
    • Examples: 'Europe/London', 'America/New_York', 'Asia/Tokyo'

Format Strings

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.)

Error Handling

Template Syntax Errors

jinja2.exceptions.TemplateSyntaxError

Raised when:

  • Missing timezone parameter: {% now %} (timezone is required)
  • Invalid template tag syntax

Runtime Errors

Invalid timezone names:

  • Arrow library may raise exceptions for unrecognized timezone specifications

Invalid format strings:

  • Python's strftime() may raise ValueError for invalid format codes

Invalid offset parameters:

  • Malformed offset strings may cause parsing errors during template rendering

Integration Notes

Dependencies

  • jinja2: Core templating engine (provides Extension base class, Environment, nodes)
  • arrow: Date/time manipulation library (provides timezone-aware date/time handling)

Compatibility

  • Python 2.7, 3.3+
  • Compatible with Jinja2 template environments
  • Thread-safe for use in web applications

Performance Considerations

  • Each {% now %} tag evaluation performs a system time call
  • Timezone conversions and offset calculations have minimal overhead via Arrow library
  • Template compilation is performed once; rendering performance is optimized for repeated use