Skip to content

Commit

Permalink
use timedelta thresholds
Browse files Browse the repository at this point in the history
  • Loading branch information
anish-work committed Dec 26, 2024
1 parent 8a9c4cf commit 3bce2f3
Showing 1 changed file with 15 additions and 18 deletions.
33 changes: 15 additions & 18 deletions daras_ai_v2/utils.py
Original file line number Diff line number Diff line change
@@ -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"

0 comments on commit 3bce2f3

Please sign in to comment.