or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-flask-moment

Formatting of dates and times in Flask templates using moment.js.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/flask-moment@1.0.x

To install, run

npx @tessl/cli install tessl/pypi-flask-moment@1.0.0

0

# Flask-Moment

1

2

Flask-Moment is a Flask extension that enhances Jinja2 templates with client-side date and time formatting capabilities using the moment.js JavaScript library. It provides a Python wrapper that generates HTML elements with moment.js directives, enabling dynamic formatting of timestamps in web applications without server-side processing.

3

4

## Package Information

5

6

- **Package Name**: Flask-Moment

7

- **Language**: Python

8

- **Installation**: `pip install Flask-Moment`

9

10

## Core Imports

11

12

```python

13

from flask_moment import Moment

14

```

15

16

For direct moment class access:

17

18

```python

19

from flask_moment import moment

20

```

21

22

For accessing constants:

23

24

```python

25

from flask_moment import default_moment_version, default_moment_sri

26

```

27

28

## Basic Usage

29

30

```python

31

from flask import Flask, render_template_string

32

from flask_moment import Moment

33

from datetime import datetime

34

35

app = Flask(__name__)

36

moment = Moment(app)

37

38

@app.route('/')

39

def index():

40

now = datetime.utcnow()

41

template = '''

42

<html>

43

<head>

44

{{ moment.include_moment() }}

45

</head>

46

<body>

47

<p>Current time: {{ moment(now).format('LLLL') }}</p>

48

<p>Time ago: {{ moment(now).fromNow(refresh=True) }}</p>

49

</body>

50

</html>

51

'''

52

return render_template_string(template, now=now)

53

54

if __name__ == '__main__':

55

app.run()

56

```

57

58

## Capabilities

59

60

### Flask Extension Setup

61

62

Initialize the Flask-Moment extension with your Flask application.

63

64

```python { .api }

65

class Moment:

66

"""Flask extension for moment.js integration."""

67

68

def __init__(self, app=None):

69

"""

70

Initialize the extension.

71

72

Args:

73

app (Flask, optional): Flask application instance

74

"""

75

76

def init_app(self, app):

77

"""

78

Initialize the extension with a Flask app.

79

80

Args:

81

app (Flask): Flask application instance

82

"""

83

84

def create(self, timestamp=None):

85

"""

86

Create a moment object via the app extension.

87

88

Args:

89

timestamp (datetime or str, optional): Timestamp to create moment from

90

91

Returns:

92

moment: Moment object instance

93

"""

94

95

def flask_moment_js(self):

96

"""

97

Get the Flask-Moment JavaScript code.

98

99

Returns:

100

str: JavaScript code for moment rendering

101

"""

102

103

@staticmethod

104

def context_processor():

105

"""

106

Provide template context processor for moment integration.

107

108

Returns:

109

dict: Template context with moment object

110

"""

111

```

112

113

### Moment Class Methods

114

115

Core functionality for moment.js library integration and locale configuration.

116

117

```python { .api }

118

class moment:

119

"""Core moment object for timestamp formatting."""

120

121

@classmethod

122

def include_moment(cls, version=default_moment_version, local_js=None, no_js=None, sri=None, with_locales=True):

123

"""

124

Include moment.js library and Flask-Moment JavaScript code.

125

126

Args:

127

version (str): Version of moment.js to include

128

local_js (str, optional): URL to local moment.js file

129

no_js (bool, optional): Skip moment.js library, include only Flask-Moment code

130

sri (str, optional): SRI hash for security

131

with_locales (bool): Include localized version of moment.js

132

133

Returns:

134

Markup: HTML script tags for moment.js and Flask-Moment

135

"""

136

137

@staticmethod

138

def locale(language='en', auto_detect=False, customization=None):

139

"""

140

Configure moment.js locale settings.

141

142

Args:

143

language (str): Language code for locale

144

auto_detect (bool): Auto-detect locale from browser

145

customization (dict, optional): Custom locale configuration

146

147

Returns:

148

Markup: HTML script tag with locale configuration

149

"""

150

151

@staticmethod

152

def lang(language):

153

"""

154

Set the moment.js language (simpler version of locale).

155

156

Args:

157

language (str): Language code

158

159

Returns:

160

Markup: HTML script tag with language configuration

161

"""

162

163

@staticmethod

164

def flask_moment_js():

165

"""

166

Get the Flask-Moment JavaScript code without moment.js library.

167

168

Returns:

169

str: JavaScript code for Flask-Moment functionality

170

"""

171

172

def __init__(self, timestamp=None, local=False):

173

"""

174

Create a moment object.

175

176

Args:

177

timestamp (datetime or str, optional): Timestamp to format

178

local (bool): Whether timestamp is in local timezone

179

"""

180

```

181

182

### Time Formatting

183

184

Format timestamps with custom format strings.

185

186

```python { .api }

187

def format(self, fmt=None, refresh=False):

188

"""

189

Format timestamp with custom formatting string.

190

191

Args:

192

fmt (str, optional): Format string as per moment.js format()

193

refresh (bool or int): Auto-refresh interval in minutes

194

195

Returns:

196

Markup: HTML span element with formatted timestamp

197

"""

198

```

199

200

### Relative Time Display

201

202

Display timestamps as relative time expressions.

203

204

```python { .api }

205

def fromNow(self, no_suffix=False, refresh=False):

206

"""

207

Display timestamp as relative time from now.

208

209

Args:

210

no_suffix (bool): Exclude "ago" suffix from output

211

refresh (bool or int): Auto-refresh interval in minutes

212

213

Returns:

214

Markup: HTML span with relative time like "2 hours ago"

215

"""

216

217

def fromTime(self, timestamp, no_suffix=False, refresh=False):

218

"""

219

Display timestamp as relative time from reference timestamp.

220

221

Args:

222

timestamp (datetime or str): Reference timestamp

223

no_suffix (bool): Exclude "ago" suffix from output

224

refresh (bool or int): Auto-refresh interval in minutes

225

226

Returns:

227

Markup: HTML span with relative time

228

"""

229

230

def toNow(self, no_suffix=False, refresh=False):

231

"""

232

Display timestamp as reverse relative time to now.

233

234

Args:

235

no_suffix (bool): Exclude "ago" suffix from output

236

refresh (bool or int): Auto-refresh interval in minutes

237

238

Returns:

239

Markup: HTML span with reverse relative time

240

"""

241

242

def toTime(self, timestamp, no_suffix=False, refresh=False):

243

"""

244

Display timestamp as relative time to reference timestamp.

245

246

Args:

247

timestamp (datetime or str): Reference timestamp

248

no_suffix (bool): Exclude "ago" suffix from output

249

refresh (bool or int): Auto-refresh interval in minutes

250

251

Returns:

252

Markup: HTML span with relative time

253

"""

254

```

255

256

### Calendar-Style Display

257

258

Display timestamps using calendar-style formatting.

259

260

```python { .api }

261

def calendar(self, refresh=False):

262

"""

263

Display timestamp using calendar-style relative time.

264

265

Args:

266

refresh (bool or int): Auto-refresh interval in minutes

267

268

Returns:

269

Markup: HTML span with calendar format like "next Sunday"

270

"""

271

```

272

273

### Numeric Time Values

274

275

Convert timestamps to numeric representations.

276

277

```python { .api }

278

def valueOf(self, refresh=False):

279

"""

280

Display timestamp as milliseconds from Unix Epoch.

281

282

Args:

283

refresh (bool or int): Auto-refresh interval in minutes

284

285

Returns:

286

Markup: HTML span with millisecond timestamp

287

"""

288

289

def unix(self, refresh=False):

290

"""

291

Display timestamp as seconds from Unix Epoch.

292

293

Args:

294

refresh (bool or int): Auto-refresh interval in minutes

295

296

Returns:

297

Markup: HTML span with Unix timestamp

298

"""

299

```

300

301

### Time Difference Calculations

302

303

Calculate and display differences between timestamps.

304

305

```python { .api }

306

def diff(self, timestamp, units, refresh=False):

307

"""

308

Calculate difference between timestamps in specified units.

309

310

Args:

311

timestamp (datetime or str): Reference timestamp to compare against

312

units (str): Units for difference ('years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds')

313

refresh (bool or int): Auto-refresh interval in minutes

314

315

Returns:

316

Markup: HTML span with time difference value

317

"""

318

```

319

320

## Types

321

322

```python { .api }

323

# External Types

324

from markupsafe import Markup # HTML-safe string type used for all HTML output

325

326

# Constants

327

default_moment_version: str # Default moment.js version ('2.29.4')

328

default_moment_sri: str # Default SRI hash for moment.js

329

330

# Template Context

331

# When Moment extension is initialized, 'moment' is available in templates

332

# Templates can access: moment(), moment.include_moment(), moment.locale(), etc.

333

```

334

335

## Configuration

336

337

Flask-Moment supports optional Flask configuration:

338

339

- `MOMENT_DEFAULT_FORMAT`: Default format string for moment.js formatting

340

341

Example:

342

```python

343

app.config['MOMENT_DEFAULT_FORMAT'] = 'YYYY-MM-DD HH:mm:ss'

344

```

345

346

## Template Usage Examples

347

348

### Basic Template Integration

349

350

```html

351

<html>

352

<head>

353

{{ moment.include_moment() }}

354

</head>

355

<body>

356

<p>Current time: {{ moment().format('LLLL') }}</p>

357

<p>Updated {{ moment(last_update).fromNow(refresh=True) }}</p>

358

</body>

359

</html>

360

```

361

362

### Advanced Template Usage

363

364

```html

365

<html>

366

<head>

367

{{ moment.include_moment() }}

368

{{ moment.locale('es') }} <!-- Spanish locale -->

369

</head>

370

<body>

371

<p>Formatted: {{ moment(timestamp).format('dddd, MMMM Do YYYY') }}</p>

372

<p>Calendar: {{ moment(timestamp).calendar() }}</p>

373

<p>Time difference: {{ moment(end_time).diff(start_time, 'hours') }} hours</p>

374

<p>Unix timestamp: {{ moment(timestamp).unix() }}</p>

375

</body>

376

</html>

377

```

378

379

### Custom JavaScript Integration

380

381

```html

382

<script>

383

{{ moment.flask_moment_js() }}

384

// Custom moment.js code can be added here

385

</script>

386

```