Skip to content

Instantly share code, notes, and snippets.

@Suor
Created September 5, 2017 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Suor/4c4e29041f4fb3401d39b443e0970b70 to your computer and use it in GitHub Desktop.
Save Suor/4c4e29041f4fb3401d39b443e0970b70 to your computer and use it in GitHub Desktop.
def plural(n, word, suffix='s'):
show_suffix = n % 10 == 1 and n % 100 != 11
return '%d %s%s' % (n, word, '' if show_suffix else suffix)
# @register.filter
def human_timedelta(delta, precision=2):
units = ['year', 'month', 'day', 'hour', 'minute']
unit_delta = [getattr(delta, unit + 's'), unit for unit in units]
terms = [plural(n, unit) for n, unit in units if n > 0]
terms = terms[:precision]
if len(terms) > 1:
return ' and '.join([', '.join(terms[:-1]), terms[-1]])
else:
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment