Flask-Moment

1.0.6 · active · verified Thu Apr 16

Flask-Moment is an extension for the Flask web application framework that simplifies the formatting and rendering of dates and times in Jinja2 templates using the client-side JavaScript library moment.js. As of its latest release, 1.0.6, the library remains active, with the most recent version released on May 28, 2024. It typically sees a few releases per year, primarily for maintenance and minor enhancements.

Common errors

Warnings

Install

Imports

Quickstart

Initialize the `Moment` extension with your Flask application. In your Jinja2 template, include `{{ moment.include_moment() }}` in the `<head>` section to load the necessary JavaScript libraries. Then, you can use the `moment()` function in your templates to format `datetime` objects or render current time, utilizing various moment.js formatting options.

from flask import Flask, render_template
from flask_moment import Moment
from datetime import datetime

app = Flask(__name__)
app.config['SECRET_KEY'] = 'a-very-secret-key'
moment = Moment(app)

@app.route('/')
def index():
    return render_template('index.html', current_time=datetime.utcnow())

# --- In templates/index.html ---
# <!DOCTYPE html>
# <html lang="en">
# <head>
#     <meta charset="UTF-8">
#     <title>Flask-Moment Example</title>
#     {{ moment.include_moment() }}
# </head>
# <body>
#     <p>The current time is: {{ moment(current_time).format('MMMM Do YYYY, h:mm:ss a') }}.</p>
#     <p>A relative time: {{ moment(current_time).fromNow() }}.</p>
# </body>
# </html>

view raw JSON →