Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify time display #47

Merged
merged 1 commit into from
May 22, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 36 additions & 12 deletions core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ def validate_discord_token(token: str) -> bool:
else:
return True

def pluralize(count: int, singular: str) -> str:
return singular if count == 1 else singular + "s"

def natural_time(
td: datetime.timedelta,
Expand All @@ -113,23 +115,45 @@ def natural_time(
future = then > now

ago = "{delta} from now" if future else "{delta} ago"

seconds = round(td.total_seconds())
years, seconds = divmod(seconds, 60 * 60 * 24 * 365)
months, seconds = divmod(seconds, 60 * 60 * 24 * 30)
weeks, seconds = divmod(seconds, 60 * 60 * 24 * 7)
days, seconds = divmod(seconds, 60 * 60 * 24)
hours, seconds = divmod(seconds, 60 * 60)
minutes, seconds = divmod(seconds, 60)

ret = ""

if weeks:
ret += f"{weeks} weeks,"
if days:
ret += f"{days} days,"
if hours:
ret += f"{hours} hours,"
if minutes:
ret += f"{minutes} minutes and "
ret += f"{seconds} seconds"

return ago.format(delta=ret)
if years:
ret += f"{years} {pluralize(years, 'year')}"
if months:
ret += f", {months} {pluralize(months, 'month')}"
elif months:
ret += f"{months} {pluralize(months, 'month')}"
elif weeks:
ret += f"{weeks} {pluralize(weeks, 'week')}"
if days:
ret += f", {days} {pluralize(days, 'day')}"
elif days:
ret += f"{days} {pluralize(days, 'day')}"

if hours and not years and not months and not weeks and not days:
if ret:
ret += ", "
ret += f"{hours} {pluralize(hours, 'hour')}"
if (
minutes
and not years
and not months
and not weeks
and not days
and not hours
):
if ret:
ret += ", "
ret += f"{minutes} {pluralize(minutes, 'minute')}"

formatted_ret = ", ".join(ret.split(", ")[:2])

return ago.format(delta=formatted_ret)
Loading