diff options
author | osmarks <osmarks> | 2021-06-14 18:06:48 +0000 |
---|---|---|
committer | osmarks <osmarks> | 2021-06-14 18:06:48 +0000 |
commit | 1f447eda8ed0fb1ba7c4ff6da8d40fe56aaddabf (patch) | |
tree | f33666313dd1f356923115dda97c474c5cb0f9ea /apioforum/fuzzy.py | |
parent | 5d394e581b108eaf1470d5d00b1699d6ade25b4c (diff) |
Implement search (SQLite FTS5)
Diffstat (limited to 'apioforum/fuzzy.py')
-rw-r--r-- | apioforum/fuzzy.py | 45 |
1 files changed, 21 insertions, 24 deletions
diff --git a/apioforum/fuzzy.py b/apioforum/fuzzy.py index 58f8c6b..94e99c9 100644 --- a/apioforum/fuzzy.py +++ b/apioforum/fuzzy.py @@ -1,35 +1,32 @@ # fuzzy datetime things -times = ( - ("year","years",365*24*60*60), # leap years aren't real - ("day","days",24*60*60), - ("hour","hours",60*60), - ("minute","minutes",60), - ("second","seconds",1), +units = ( + ("y", "year","years",365*24*60*60), # leap years aren't real + ("d", "day","days",24*60*60), + ("h", "hour","hours",60*60), + ("m", "minute","minutes",60), + ("s", "second","seconds",1), ) -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone -def fuzzy(seconds,ago=True): - if isinstance(seconds,timedelta): +def fuzzy(seconds, ago=False): + if isinstance(seconds, timedelta): seconds = seconds.total_seconds() - elif isinstance(seconds,datetime): - seconds = (seconds-datetime.now()).total_seconds() + elif isinstance(seconds, datetime): + seconds = (seconds.replace(tzinfo=timezone.utc) - datetime.now(tz=timezone.utc)).total_seconds() fmt = "{}" + buf = "" if ago: fmt = "in {}" if seconds > 0 else "{} ago" + elif seconds > 0: fmt = "in {}" seconds = abs(seconds) - for t in times: - if seconds >= t[2]: - rounded = round((seconds / t[2])*100)/100 - if int(rounded) == rounded: - rounded = int(rounded) - if rounded == 1: - word = t[0] - else: - word = t[1] - return fmt.format(f'{rounded} {word}') - else: - return "now" - + for short, _, _, unit_length in units: + if seconds >= unit_length: + qty = seconds // unit_length + buf += str(int(qty)) + short + seconds -= qty * unit_length + if not buf: return "now" + + return fmt.format(buf) |