or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# Jinja2-Time

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: jinja2-time

7

- **Package Type**: pypi

8

- **Language**: Python

9

- **Installation**: `pip install jinja2-time`

10

- **Dependencies**: jinja2, arrow

11

12

## Core Imports

13

14

```python

15

from jinja2_time import TimeExtension

16

```

17

18

Using with Jinja2 string-based extension loading:

19

20

```python

21

from jinja2 import Environment

22

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

23

```

24

25

## Basic Usage

26

27

```python

28

from jinja2 import Environment

29

from jinja2_time import TimeExtension

30

31

# Setup Jinja2 environment with the extension

32

env = Environment(extensions=[TimeExtension])

33

34

# Basic usage with default format (YYYY-MM-DD)

35

template = env.from_string("{% now 'utc' %}")

36

result = template.render() # e.g., "2023-12-09"

37

38

# Custom datetime format

39

template = env.from_string("{% now 'utc', '%a, %d %b %Y %H:%M:%S' %}")

40

result = template.render() # e.g., "Thu, 09 Dec 2023 15:30:45"

41

42

# Using local timezone

43

template = env.from_string("{% now 'local' %}")

44

result = template.render()

45

46

# Time offset operations

47

template = env.from_string("{% now 'utc' + 'hours=2, minutes=30' %}")

48

result = template.render() # Current time + 2.5 hours

49

50

template = env.from_string("{% now 'utc' - 'days=1, hours=6' %}")

51

result = template.render() # Yesterday, 6 hours earlier

52

53

# Configure default datetime format

54

env.datetime_format = '%Y-%m-%d %H:%M:%S'

55

template = env.from_string("{% now 'utc' %}")

56

result = template.render() # Uses custom default format

57

```

58

59

## Capabilities

60

61

### Extension Class

62

63

The main extension class that integrates time functionality into Jinja2 templates.

64

65

```python { .api }

66

class TimeExtension(jinja2.ext.Extension):

67

"""

68

Jinja2 extension for time and date functionality.

69

70

Attributes:

71

tags: Set of supported template tags (contains 'now')

72

"""

73

74

def __init__(self, environment):

75

"""

76

Initialize the TimeExtension.

77

78

Parameters:

79

- environment: jinja2.Environment instance

80

81

Effects:

82

- Adds datetime_format attribute to environment with default '%Y-%m-%d'

83

"""

84

85

def parse(self, parser):

86

"""

87

Parse the template tag syntax and return appropriate AST nodes.

88

89

Inherited from jinja2.ext.Extension. Processes {% now %} template tags

90

and determines whether to handle basic time display or offset operations.

91

92

Parameters:

93

- parser: jinja2.lexer.TokenStream parser instance

94

95

Returns:

96

- jinja2.nodes.Output node containing the processed time expression

97

"""

98

```

99

100

### Template Tag Syntax

101

102

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

103

104

#### Basic Time Display

105

106

```jinja2 { .api }

107

{% now 'timezone' %}

108

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

109

```

110

111

**Parameters:**

112

- `timezone`: Timezone specification

113

- `'utc'` - UTC timezone

114

- `'local'` - Local system timezone

115

- IANA timezone names (e.g., `'Europe/Berlin'`, `'America/New_York'`)

116

- `format`: Python strftime format string (optional)

117

- If omitted, uses `environment.datetime_format` (default: `'%Y-%m-%d'`)

118

119

#### Time Offset Operations

120

121

```jinja2 { .api }

122

{% now 'timezone' + 'offset_params' %}

123

{% now 'timezone' - 'offset_params' %}

124

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

125

```

126

127

**Parameters:**

128

- `offset_params`: Comma-separated time offset parameters in `interval=value` format

129

- `years=N`, `months=N`, `weeks=N`, `days=N`

130

- `hours=N`, `minutes=N`, `seconds=N`, `microseconds=N`

131

- Examples: `'hours=2'`, `'days=1, hours=3, minutes=30'`

132

- Supports fractional values: `'hours=2.5'`, `'days=1.25'`

133

- Format: Each parameter as `interval=value`, separated by commas with optional spaces

134

135

### Environment Configuration

136

137

```python { .api }

138

# Environment attribute added by TimeExtension

139

environment.datetime_format: str

140

```

141

142

**Usage:**

143

```python

144

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

145

```

146

147

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

148

149

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

150

151

### Package Metadata

152

153

```python { .api }

154

__version__: str = '0.2.0'

155

__author__: str = 'Raphael Pierzina'

156

__email__: str = 'raphael@hackebrot.de'

157

__all__: List[str] = ['TimeExtension']

158

```

159

160

## Types

161

162

### Extension Inheritance

163

164

```python { .api }

165

class TimeExtension(jinja2.ext.Extension):

166

"""

167

Inherits from jinja2.ext.Extension base class.

168

169

Key inherited methods:

170

- parse(self, parser): Processes template tag syntax

171

- call_method(self, name, args, lineno): Calls extension methods from templates

172

"""

173

174

tags: Set[str] = {'now'} # Supported template tags

175

```

176

177

### Timezone Support

178

179

Supported timezone formats:

180

- `'utc'` - Coordinated Universal Time

181

- `'local'` - Local system timezone

182

- IANA timezone names (full list depends on system configuration)

183

- Examples: `'Europe/London'`, `'America/New_York'`, `'Asia/Tokyo'`

184

185

### Format Strings

186

187

Supports Python's `strftime()` format codes:

188

189

**Common format codes:**

190

- `%Y` - Year with century (e.g., 2023)

191

- `%m` - Month as zero-padded decimal (01-12)

192

- `%d` - Day as zero-padded decimal (01-31)

193

- `%H` - Hour as zero-padded decimal (00-23)

194

- `%M` - Minute as zero-padded decimal (00-59)

195

- `%S` - Second as zero-padded decimal (00-59)

196

- `%a` - Abbreviated weekday name (Mon, Tue, etc.)

197

- `%A` - Full weekday name (Monday, Tuesday, etc.)

198

- `%b` - Abbreviated month name (Jan, Feb, etc.)

199

- `%B` - Full month name (January, February, etc.)

200

- `%Z` - Timezone name

201

- `%z` - UTC offset (+0000, -0500, etc.)

202

203

## Error Handling

204

205

### Template Syntax Errors

206

207

```python

208

jinja2.exceptions.TemplateSyntaxError

209

```

210

211

**Raised when:**

212

- Missing timezone parameter: `{% now %}` (timezone is required)

213

- Invalid template tag syntax

214

215

### Runtime Errors

216

217

**Invalid timezone names:**

218

- Arrow library may raise exceptions for unrecognized timezone specifications

219

220

**Invalid format strings:**

221

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

222

223

**Invalid offset parameters:**

224

- Malformed offset strings may cause parsing errors during template rendering

225

226

## Integration Notes

227

228

### Dependencies

229

230

- **jinja2**: Core templating engine (provides Extension base class, Environment, nodes)

231

- **arrow**: Date/time manipulation library (provides timezone-aware date/time handling)

232

233

### Compatibility

234

235

- Python 2.7, 3.3+

236

- Compatible with Jinja2 template environments

237

- Thread-safe for use in web applications

238

239

### Performance Considerations

240

241

- Each `{% now %}` tag evaluation performs a system time call

242

- Timezone conversions and offset calculations have minimal overhead via Arrow library

243

- Template compilation is performed once; rendering performance is optimized for repeated use