Flask Format datetime in a Jinja2 template


Example

Filters can either be defined in a method and then added to Jinja's filters dictionary, or defined in a method decorated with Flask.template_filter.

Defining and registering later:

def format_datetime(value, format="%d %b %Y %I:%M %p"):
    """Format a date time to (Default): d Mon YYYY HH:MM P"""
    if value is None:
        return ""
    return value.strftime(format)

# Register the template filter with the Jinja Environment
app.jinja_env.filters['formatdatetime'] = format_datetime

Defining with decorator:

@app.template_filter('formatdatetime')
def format_datetime(value, format="%d %b %Y %I:%M %p"):
    """Format a date time to (Default): d Mon YYYY HH:MM P"""
    if value is None:
        return ""
    return value.strftime(format)