Jinja2
date formatting
template engine
Python
web development

How to format a date in Jinja2

Codemia Knowledge Hub ·

Format dates in Jinja2 by passing Python datetime objects to the template and formatting them with a filter that calls strftime. Keep parsing and timezone conversion in Python, and let templates handle display only.

Register a reusable date filter

Register a custom filter in your Flask or Jinja environment so the formatting logic lives in one place instead of being repeated across templates:

python
1from datetime import datetime
2from flask import Flask
3
4app = Flask(__name__)
5
6@app.template_filter('fmt_date')
7def fmt_date(value, pattern='%Y-%m-%d'):
8    if value is None:
9        return ''
10    if isinstance(value, str):
11        value = datetime.fromisoformat(value)
12    return value.strftime(pattern)

The filter returns an empty string for None, parses ISO strings with datetime.fromisoformat, and accepts a strftime pattern that defaults to %Y-%m-%d. Verify one normal value and one edge case (such as a missing date) before building on it.

Use the filter with a fallback

In templates, pass the display pattern to the filter and handle missing values explicitly:

jinja
1{% if user.created_at %}
2  <span>Joined {{ user.created_at|fmt_date('%b %d, %Y') }}</span>
3{% else %}
4  <span>Joined date unavailable</span>
5{% endif %}

Display-specific patterns such as '%b %d, %Y' belong in the template, while parsing stays in Python. The if check keeps the page from breaking when a timestamp is missing.

Locales and timezones

For internationalized apps, convert to the user's timezone and use locale-aware formatting libraries before rendering. Hardcoded formats often break expectations in multi-region products.

Testing and operating the filter

Add a small regression suite that covers expected inputs, edge cases such as None, and at least one failure path, with representative test data. Keep it fast enough to run in CI so contributors can confirm the filter still behaves after dependency upgrades or refactoring, without manual spot checks.

Many recurring date bugs come from environment differences rather than syntax, so agree on library versions, the runtime environment and who owns the related configuration. Log only the decisions that matter for debugging, such as a value that failed to parse, rather than every render.

Plan a fallback before release too. Correct code can still fail on unexpected data or after a dependency update, and the else branch in the template above is a simple example of degrading gracefully instead of breaking the page.

Mistakes to avoid

  • Formatting raw strings in templates without validating how they parse.
  • Skipping timezone conversion before display.
  • Duplicating date format patterns across many templates.
  • Using locale-specific formats without an explicit locale.
  • Forgetting null handling, so pages break on missing timestamps.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms