Skip to content

Instantly share code, notes, and snippets.

@danila-schelkov
Last active December 17, 2022 12:51
Show Gist options
  • Save danila-schelkov/7d9a3f554848269623d28f3326c9b3aa to your computer and use it in GitHub Desktop.
Save danila-schelkov/7d9a3f554848269623d28f3326c9b3aa to your computer and use it in GitHub Desktop.
a little function, that converts seconds to pretty time string
UNIT_NAMES = ('ms', 'sec', 'min', 'hour', 'day', 'week')
UNIT_DIVIDERS = (1, 60, 60, 24, 7, 1)
UNIT_FORMATTERS = (lambda unit: round(unit * 1000), round, round, round, round, round)
def time_to_string(value: float):
assert value >= 0, 'Time cannot be negative.'
assert len(UNIT_NAMES) == len(UNIT_DIVIDERS) == len(UNIT_FORMATTERS), 'Units count does not match.'
times = []
for i in range(len(UNIT_DIVIDERS)):
divider = UNIT_DIVIDERS[i]
unit_name = UNIT_NAMES[i]
unit_formatter = UNIT_FORMATTERS[i]
unit = value % divider
value //= divider
if unit_formatter is not None:
unit = unit_formatter(unit)
if unit == 0:
continue
times.append(f'{unit} {unit_name}')
return ' '.join(times[::-1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment