Created
May 15, 2015 23:32
-
-
Save bsnux/481afe07e8864f53716c to your computer and use it in GitHub Desktop.
Display number of seconds in human format
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def humanize_seconds(seconds, granularity=2): | |
intervals = ( | |
('weeks', 604800), # 60 * 60 * 24 * 7 | |
('days', 86400), # 60 * 60 * 24 | |
('hours', 3600), # 60 * 60 | |
('minutes', 60), | |
('seconds', 1), | |
) | |
result = [] | |
for name, count in intervals: | |
value = seconds // count | |
if value: | |
seconds -= value * count | |
if value == 1: | |
name = name.rstrip('s') | |
result.append("{} {}".format(value, name)) | |
return ', '.join(result[:granularity]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment