Skip to content

Commit 9a02d2b

Browse files
authored
Simplify time display (#47)
1 parent e2f92b8 commit 9a02d2b

File tree

1 file changed

+36
-12
lines changed

1 file changed

+36
-12
lines changed

core/utils.py

Lines changed: 36 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,8 @@ def validate_discord_token(token: str) -> bool:
100100
else:
101101
return True
102102

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

104106
def natural_time(
105107
td: datetime.timedelta,
@@ -113,23 +115,45 @@ def natural_time(
113115
future = then > now
114116

115117
ago = "{delta} from now" if future else "{delta} ago"
116-
117118
seconds = round(td.total_seconds())
119+
years, seconds = divmod(seconds, 60 * 60 * 24 * 365)
120+
months, seconds = divmod(seconds, 60 * 60 * 24 * 30)
118121
weeks, seconds = divmod(seconds, 60 * 60 * 24 * 7)
119122
days, seconds = divmod(seconds, 60 * 60 * 24)
120123
hours, seconds = divmod(seconds, 60 * 60)
121124
minutes, seconds = divmod(seconds, 60)
122125

123126
ret = ""
124127

125-
if weeks:
126-
ret += f"{weeks} weeks,"
127-
if days:
128-
ret += f"{days} days,"
129-
if hours:
130-
ret += f"{hours} hours,"
131-
if minutes:
132-
ret += f"{minutes} minutes and "
133-
ret += f"{seconds} seconds"
134-
135-
return ago.format(delta=ret)
128+
if years:
129+
ret += f"{years} {pluralize(years, 'year')}"
130+
if months:
131+
ret += f", {months} {pluralize(months, 'month')}"
132+
elif months:
133+
ret += f"{months} {pluralize(months, 'month')}"
134+
elif weeks:
135+
ret += f"{weeks} {pluralize(weeks, 'week')}"
136+
if days:
137+
ret += f", {days} {pluralize(days, 'day')}"
138+
elif days:
139+
ret += f"{days} {pluralize(days, 'day')}"
140+
141+
if hours and not years and not months and not weeks and not days:
142+
if ret:
143+
ret += ", "
144+
ret += f"{hours} {pluralize(hours, 'hour')}"
145+
if (
146+
minutes
147+
and not years
148+
and not months
149+
and not weeks
150+
and not days
151+
and not hours
152+
):
153+
if ret:
154+
ret += ", "
155+
ret += f"{minutes} {pluralize(minutes, 'minute')}"
156+
157+
formatted_ret = ", ".join(ret.split(", ")[:2])
158+
159+
return ago.format(delta=formatted_ret)

0 commit comments

Comments
 (0)