]> rtime.felk.cvut.cz Git - coffee/coffee-flask.git/commitdiff
Add humanize filter for Jinja2 templates
authorMichal Sojka <michal.sojka@cvut.cz>
Tue, 18 Aug 2020 17:24:22 +0000 (19:24 +0200)
committerMichal Sojka <michal.sojka@cvut.cz>
Wed, 19 Aug 2020 13:06:21 +0000 (15:06 +0200)
This filter converts date/time values into relative time strings such
as "an hour ago".

It will be used in later commits.

app.py

diff --git a/app.py b/app.py
index b4d7e41d4a7e90175e08c8b8a71bccce9560a393..0e0564aa398d4ad8fc256edf80852914b6ad097e 100644 (file)
--- a/app.py
+++ b/app.py
@@ -11,10 +11,11 @@ from io import BytesIO
 import coffee_db as db
 import time
 import sys
-from datetime import date, timedelta
+from datetime import date, timedelta, datetime, timezone
 
 from json import loads
 from requests import post
+import jinja2
 
 db.init_db()
 app = Flask(__name__)
@@ -22,6 +23,53 @@ CORS(app, supports_credentials=True)
 app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
 
 
+# Inspired by https://shubhamjain.co/til/how-to-render-human-readable-time-in-jinja/,
+# updated to our needs
+def humanize_ts(time):
+    """
+    Convert date in ISO format to relative, human readable string
+    like 'an hour ago', 'Yesterday', '3 months ago',
+    'just now', etc
+    """
+    if jinja2.is_undefined(time):
+        return time
+    now = datetime.now(timezone.utc)
+    if time[-1] == 'Z':     # Convert Zulu time zone to datetime compatible format
+        time = time[0:-1] + '+00:00'
+    diff = now - datetime.fromisoformat(time)
+    second_diff = diff.seconds
+    day_diff = diff.days
+
+    if day_diff < 0:
+        return ''
+
+    if day_diff == 0:
+        if second_diff < 10:
+            return "just now"
+        if second_diff < 60:
+            return str(int(second_diff)) + " seconds ago"
+        if second_diff < 120:
+            return "a minute ago"
+        if second_diff < 3600:
+            return str(int(second_diff / 60)) + " minutes ago"
+        if second_diff < 7200:
+            return "an hour ago"
+        if second_diff < 86400:
+            return str(int(second_diff / 3600)) + " hours ago"
+    if day_diff == 1:
+        return "Yesterday"
+    if day_diff < 7:
+        return str(day_diff) + " days ago"
+    if day_diff < 31:
+        return str(int(day_diff / 7)) + " weeks ago"
+    if day_diff < 365:
+        return str(int(day_diff / 30)) + " months ago"
+    return str(int(day_diff / 365)) + " years ago"
+
+
+app.jinja_env.filters['humanize'] = humanize_ts
+
+
 @app.route('/')
 def hello():
     if "uid" in session: