Skip to content

Instantly share code, notes, and snippets.

@lyudmil-mitev
Created July 4, 2011 15:26
Show Gist options
  • Save lyudmil-mitev/1063489 to your computer and use it in GitHub Desktop.
Save lyudmil-mitev/1063489 to your computer and use it in GitHub Desktop.
Humanize time intervals. humanize_time(173, "hours") --> [(1, 'week'), (5, 'hours')]
#!/usr/bin/env python
INTERVALS = [1, 60, 3600, 86400, 604800, 2419200, 29030400]
NAMES = [('second', 'seconds'),
('minute', 'minutes'),
('hour', 'hours'),
('day', 'days'),
('week', 'weeks'),
('month', 'months'),
('year', 'years')]
NAMES_SINGULAR = ['second', 'minute', 'hour', 'day', 'week', 'month', 'year']
def humanize_time(amount, units):
result = []
unit = map(lambda a: a[1], NAMES).index(units)
# Convert to seconds
amount = amount * INTERVALS[unit]
for i in range(len(NAMES)-1, -1, -1):
a = amount / INTERVALS[i]
if a > 0:
result.append( (a, NAMES[i][1 % a]) )
amount -= a * INTERVALS[i]
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment