Flask - Convert date from yyyy-mm-dd to dd-mm-yyyy in jinja2
We can change the date format using Jinja2 filters. Jinja2 filters are used to transform data into another.
Configure Jinja2 environment in the following manner.
#define function for convert yyyy-mm-dd to dd-mm-yyyy def format_datetime(value, format="%d-%m-%Y"): if value is None: return "" return datetime.strptime(value,"%Y-%m-%d").strftime(format) #configured Jinja2 environment with user defined app.jinja_env.filters['date_format']=format_datetime
Use the filter variable in the following manner.
<p>{{ row['cdate'] | date_format }}</p> <p>{{ row['cdate'] | date_format("%b %d - %Y") }}</p>
The complete code is as follows
app.py
from flask import Flask,render_template from datetime import datetime app=Flask(__name__) #define function for convert yyyy-mm-dd to dd-mm-yyyy def format_datetime(value, format="%d-%m-%Y"): if value is None: return "" return datetime.strptime(value,"%Y-%m-%d").strftime(format) #configured Jinja2 environment with user defined app.jinja_env.filters['date_format']=format_datetime @app.route("/") @app.route("/index") def index(): data={'cdate':'2022-01-17'} return render_template("index.html",row=data) if(__name__=='__main__'): app.run(debug=True)
index.html
<!-- Output Format : 17-01-2022 --> <p>{{ row['cdate'] | date_format }}</p> <!-- Output Format : 17 Jan 2022 --> <p>{{ row['cdate'] | date_format("%b %d - %Y") }}</p> <!-- Output Format : Mon January 2022 --> <p>{{ row['cdate'] | date_format("%a - %B - %Y") }}</p>