From 3bce2f377568d644c365f6401b919b7714c3bf6d Mon Sep 17 00:00:00 2001 From: anish-work Date: Fri, 27 Dec 2024 04:29:12 +0530 Subject: [PATCH] use timedelta thresholds --- daras_ai_v2/utils.py | 33 +++++++++++++++------------------ 1 file changed, 15 insertions(+), 18 deletions(-) diff --git a/daras_ai_v2/utils.py b/daras_ai_v2/utils.py index e728b4d76..5ba6a875c 100644 --- a/daras_ai_v2/utils.py +++ b/daras_ai_v2/utils.py @@ -1,22 +1,19 @@ from django.utils import timezone -from datetime import timedelta +from datetime import timedelta, datetime +THRESHOLDS = [ + (timedelta(days=365), "y"), + (timedelta(days=30), "mo"), + (timedelta(days=1), "d"), + (timedelta(hours=1), "h"), + (timedelta(minutes=1), "m"), + (timedelta(seconds=3), "s"), +] -def get_relative_time(timestamp): - diff = timezone.now() - timestamp - seconds = diff.total_seconds() - if seconds < 2: - return "Just now" - if seconds < timedelta(minutes=1).total_seconds(): - return f"{int(seconds)}s ago" - elif seconds < timedelta(hours=1).total_seconds(): - return f"{int(seconds/timedelta(minutes=1).total_seconds())}m ago" - elif seconds < timedelta(days=1).total_seconds(): - return f"{int(seconds/timedelta(hours=1).total_seconds())}h ago" - elif seconds < timedelta(days=30).total_seconds(): - return f"{int(seconds/timedelta(days=1).total_seconds())}d ago" - elif seconds < timedelta(days=365).total_seconds(): - return f"{int(seconds/timedelta(days=30).total_seconds())}mo ago" - else: - return f"{int(seconds/timedelta(days=365).total_seconds())}y ago" +def get_relative_time(timestamp: datetime) -> str: + diff = timezone.now() - timestamp + for threshold, unit in THRESHOLDS: + if diff >= threshold: + return f"{round(diff / threshold)}{unit} ago" + return "Just now"