Flask custom time filter

Keywords: Python github Pycharm

About the Flask filter

The function of the filter provided by Flask is limited, and it can't meet the user's requirements in many cases.
Therefore, Flask provides the user with a template filter decorator, which is used to create user-defined filters

Time display

Regular users of blogs will notice that the general rules for displaying blog publishing time are as follows:

Time slot Display format
Within 1 minutes just
1 to 60 minutes How many minutes ago
1-24 hours How many hours ago
1 to 30 days How many days ago?
More than 30 days. Specific time
Non time data Original content (code adaptive exception scenario)

Time filter

# -*- coding: utf-8 -*-
# @Author: Wang Xiang
# @JianShu: Qingfeng Python
# @Date     : 2019/5/23 23:56
# @Software : PyCharm
# @version  : Python 3.6.8
# @File     : app.py

from flask import Flask, render_template
import datetime

app = Flask(__name__)

_now = datetime.datetime.now()


@app.template_filter("time_filter")
def time_filter(time):
    if not isinstance(time, datetime.datetime):
        return time
    _period = (_now - time).total_seconds()
    if _period < 60:
        return "just"
    elif 60 <= _period < 3600:
        return "%s Minutes ago" % int(_period / 60)
    elif 3600 <= _period < 86400:
        return "%s Hours ago" % int(_period / 3600)
    elif 86400 <= _period < 2592000:
        return "%s Days ago" % int(_period / 86400)
    else:
        return time.strftime('%Y-%m-%d %H:%M')


@app.route('/')
def index():
    timeList = [
        'abcd',
        _now,
        _now - datetime.timedelta(minutes=5),
        _now - datetime.timedelta(hours=10),
        _now - datetime.timedelta(days=15),
        _now - datetime.timedelta(days=150)
    ]

    return render_template('index.html', timeList=timeList)


if __name__ == '__main__':
    app.run()

Corresponding HTML basic template:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Intelligent display time</title>
    {% for time in timeList %}
        <ul>
            <li>
                <p>{{time}}</p>
                <p>{{time|time_filter}}</p>
            </li>

        </ul>
    {% endfor %}
</head>
<body>

</body>
</html>

Code implementation effect

github: https://github.com/KingUranus/FlaskTests

© by: Qingfeng Python If you need to reprint the original, please indicate
Welcome everyone to pay attention to my public number Qingfeng Python

Posted by westminster86 on Sat, 02 Nov 2019 06:05:03 -0700