]> rtime.felk.cvut.cz Git - coffee/coffee-flask.git/commitdiff
Return last_events as datetime objects rather than as strings
authorMichal Sojka <michal.sojka@cvut.cz>
Thu, 20 Aug 2020 20:17:17 +0000 (22:17 +0200)
committerMichal Sojka <michal.sojka@cvut.cz>
Fri, 21 Aug 2020 10:27:23 +0000 (12:27 +0200)
This simplifies date-related filters - humanize_ts in this commit,
date_filter in the next commit.

app.py
coffee_db.py

diff --git a/app.py b/app.py
index 9301ced0d64b9823e778b94fdd5ae060ceb7fc09..2a4b96b988fcee1e9bfb583ef3d07b540f00eb59 100644 (file)
--- a/app.py
+++ b/app.py
@@ -39,10 +39,7 @@ def humanize_ts(time, max_interval="years"):
     if max_interval not in ["years", "days"]:
         raise ValueError
 
-    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)
+    diff = datetime.now(timezone.utc) - time
     second_diff = diff.seconds
     day_diff = diff.days
 
index 7fddd8e00336c664bda76f761660ee0d4b342bc1..810ed8e41ffeebd9ba60dc091e7a6e9dc34e82d0 100644 (file)
@@ -1,5 +1,6 @@
 import sqlite3
 import os
+from datetime import datetime
 
 dbdir = os.path.dirname(__file__)
 dbdef = os.path.join(dbdir, "coffee_db.sql")
@@ -219,14 +220,21 @@ def drink_count(uid=None, start=None, stop=None):
                           + " and ".join(clauses) + " group by fl.type "
                           "order by fl.ord asc", args))
 
+def sqlite_timestring_to_datetime(timestring):
+    if timestring[-1] == 'Z':     # Convert Zulu time zone to datetime compatible format
+        timestring = timestring[0:-1] + '+00:00'
+    return datetime.fromisoformat(timestring)
 
 def last_events():
     """Return mapping with event names as keys and SQLite time string of
     the last event as values.
     """
     conn, c = open_db()
-    res = dict(c.execute("""select name, MAX(time)
-                            from events as e left join event_types as et on e.event_type = et.id
-                            group by name"""))
+    res = {}
+    for name, time in c.execute("""select name, MAX(time)
+                                from events as e left join event_types as et on e.event_type = et.id
+                                group by name"""):
+        res[name] = sqlite_timestring_to_datetime(time)
+
     close_db(conn)
     return res