Skip to content

Instantly share code, notes, and snippets.

@Olegt0rr
Last active July 21, 2023 08:53
Show Gist options
  • Save Olegt0rr/5b2ca8aa83d720e87e3ba82421ae7e99 to your computer and use it in GitHub Desktop.
Save Olegt0rr/5b2ca8aa83d720e87e3ba82421ae7e99 to your computer and use it in GitHub Desktop.
Time to text converter
# _() - is a i18n translator function
FULL_MINUTE = 60
FULL_HOUR = 60 * FULL_MINUTE
FULL_DAY = 24 * FULL_HOUR
HIDE_SECONDS_AFTER_MIN = 3
def time_to_text(seconds: int | float) -> str:
"""Receive total seconds and return text quantity of days, hours, minutes and seconds."""
days, remainder = divmod(round(seconds), FULL_DAY)
hours, remainder = divmod(remainder, FULL_HOUR)
minutes, seconds = divmod(remainder, FULL_MINUTE)
time_list = []
if days:
time_list.append(_('{n} day', '{n} days', n=days).format(n=days))
if hours:
time_list.append(_('{n} hour', '{n} hours', n=hours).format(n=hours))
if minutes:
time_list.append(_('{n} minute', '{n} minutes', n=minutes).format(n=minutes))
if seconds and not hours and minutes < HIDE_SECONDS_AFTER_MIN:
time_list.append(_('{n} second', '{n} seconds', n=seconds).format(n=seconds))
if time_list:
return ' '.join(time_list)
return _('now')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment