Formatting of dates and times in Flask templates using moment.js.
npx @tessl/cli install tessl/pypi-flask-moment@1.0.0Flask-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.
pip install Flask-Momentfrom flask_moment import MomentFor direct moment class access:
from flask_moment import momentFor accessing constants:
from flask_moment import default_moment_version, default_moment_srifrom flask import Flask, render_template_string
from flask_moment import Moment
from datetime import datetime
app = Flask(__name__)
moment = Moment(app)
@app.route('/')
def index():
now = datetime.utcnow()
template = '''
<html>
<head>
{{ moment.include_moment() }}
</head>
<body>
<p>Current time: {{ moment(now).format('LLLL') }}</p>
<p>Time ago: {{ moment(now).fromNow(refresh=True) }}</p>
</body>
</html>
'''
return render_template_string(template, now=now)
if __name__ == '__main__':
app.run()Initialize the Flask-Moment extension with your Flask application.
class Moment:
"""Flask extension for moment.js integration."""
def __init__(self, app=None):
"""
Initialize the extension.
Args:
app (Flask, optional): Flask application instance
"""
def init_app(self, app):
"""
Initialize the extension with a Flask app.
Args:
app (Flask): Flask application instance
"""
def create(self, timestamp=None):
"""
Create a moment object via the app extension.
Args:
timestamp (datetime or str, optional): Timestamp to create moment from
Returns:
moment: Moment object instance
"""
def flask_moment_js(self):
"""
Get the Flask-Moment JavaScript code.
Returns:
str: JavaScript code for moment rendering
"""
@staticmethod
def context_processor():
"""
Provide template context processor for moment integration.
Returns:
dict: Template context with moment object
"""Core functionality for moment.js library integration and locale configuration.
class moment:
"""Core moment object for timestamp formatting."""
@classmethod
def include_moment(cls, version=default_moment_version, local_js=None, no_js=None, sri=None, with_locales=True):
"""
Include moment.js library and Flask-Moment JavaScript code.
Args:
version (str): Version of moment.js to include
local_js (str, optional): URL to local moment.js file
no_js (bool, optional): Skip moment.js library, include only Flask-Moment code
sri (str, optional): SRI hash for security
with_locales (bool): Include localized version of moment.js
Returns:
Markup: HTML script tags for moment.js and Flask-Moment
"""
@staticmethod
def locale(language='en', auto_detect=False, customization=None):
"""
Configure moment.js locale settings.
Args:
language (str): Language code for locale
auto_detect (bool): Auto-detect locale from browser
customization (dict, optional): Custom locale configuration
Returns:
Markup: HTML script tag with locale configuration
"""
@staticmethod
def lang(language):
"""
Set the moment.js language (simpler version of locale).
Args:
language (str): Language code
Returns:
Markup: HTML script tag with language configuration
"""
@staticmethod
def flask_moment_js():
"""
Get the Flask-Moment JavaScript code without moment.js library.
Returns:
str: JavaScript code for Flask-Moment functionality
"""
def __init__(self, timestamp=None, local=False):
"""
Create a moment object.
Args:
timestamp (datetime or str, optional): Timestamp to format
local (bool): Whether timestamp is in local timezone
"""Format timestamps with custom format strings.
def format(self, fmt=None, refresh=False):
"""
Format timestamp with custom formatting string.
Args:
fmt (str, optional): Format string as per moment.js format()
refresh (bool or int): Auto-refresh interval in minutes
Returns:
Markup: HTML span element with formatted timestamp
"""Display timestamps as relative time expressions.
def fromNow(self, no_suffix=False, refresh=False):
"""
Display timestamp as relative time from now.
Args:
no_suffix (bool): Exclude "ago" suffix from output
refresh (bool or int): Auto-refresh interval in minutes
Returns:
Markup: HTML span with relative time like "2 hours ago"
"""
def fromTime(self, timestamp, no_suffix=False, refresh=False):
"""
Display timestamp as relative time from reference timestamp.
Args:
timestamp (datetime or str): Reference timestamp
no_suffix (bool): Exclude "ago" suffix from output
refresh (bool or int): Auto-refresh interval in minutes
Returns:
Markup: HTML span with relative time
"""
def toNow(self, no_suffix=False, refresh=False):
"""
Display timestamp as reverse relative time to now.
Args:
no_suffix (bool): Exclude "ago" suffix from output
refresh (bool or int): Auto-refresh interval in minutes
Returns:
Markup: HTML span with reverse relative time
"""
def toTime(self, timestamp, no_suffix=False, refresh=False):
"""
Display timestamp as relative time to reference timestamp.
Args:
timestamp (datetime or str): Reference timestamp
no_suffix (bool): Exclude "ago" suffix from output
refresh (bool or int): Auto-refresh interval in minutes
Returns:
Markup: HTML span with relative time
"""Display timestamps using calendar-style formatting.
def calendar(self, refresh=False):
"""
Display timestamp using calendar-style relative time.
Args:
refresh (bool or int): Auto-refresh interval in minutes
Returns:
Markup: HTML span with calendar format like "next Sunday"
"""Convert timestamps to numeric representations.
def valueOf(self, refresh=False):
"""
Display timestamp as milliseconds from Unix Epoch.
Args:
refresh (bool or int): Auto-refresh interval in minutes
Returns:
Markup: HTML span with millisecond timestamp
"""
def unix(self, refresh=False):
"""
Display timestamp as seconds from Unix Epoch.
Args:
refresh (bool or int): Auto-refresh interval in minutes
Returns:
Markup: HTML span with Unix timestamp
"""Calculate and display differences between timestamps.
def diff(self, timestamp, units, refresh=False):
"""
Calculate difference between timestamps in specified units.
Args:
timestamp (datetime or str): Reference timestamp to compare against
units (str): Units for difference ('years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds')
refresh (bool or int): Auto-refresh interval in minutes
Returns:
Markup: HTML span with time difference value
"""# External Types
from markupsafe import Markup # HTML-safe string type used for all HTML output
# Constants
default_moment_version: str # Default moment.js version ('2.29.4')
default_moment_sri: str # Default SRI hash for moment.js
# Template Context
# When Moment extension is initialized, 'moment' is available in templates
# Templates can access: moment(), moment.include_moment(), moment.locale(), etc.Flask-Moment supports optional Flask configuration:
MOMENT_DEFAULT_FORMAT: Default format string for moment.js formattingExample:
app.config['MOMENT_DEFAULT_FORMAT'] = 'YYYY-MM-DD HH:mm:ss'<html>
<head>
{{ moment.include_moment() }}
</head>
<body>
<p>Current time: {{ moment().format('LLLL') }}</p>
<p>Updated {{ moment(last_update).fromNow(refresh=True) }}</p>
</body>
</html><html>
<head>
{{ moment.include_moment() }}
{{ moment.locale('es') }} <!-- Spanish locale -->
</head>
<body>
<p>Formatted: {{ moment(timestamp).format('dddd, MMMM Do YYYY') }}</p>
<p>Calendar: {{ moment(timestamp).calendar() }}</p>
<p>Time difference: {{ moment(end_time).diff(start_time, 'hours') }} hours</p>
<p>Unix timestamp: {{ moment(timestamp).unix() }}</p>
</body>
</html><script>
{{ moment.flask_moment_js() }}
// Custom moment.js code can be added here
</script>