Created
January 6, 2019 06:19
-
-
Save kingspp/e8c470e1861445a9076017e9450c0437 to your computer and use it in GitHub Desktop.
Time delta in a human readable format
This file contains 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_time_delta(td_object): | |
seconds = td_object | |
periods = [ | |
('year', 60 * 60 * 24 * 365), | |
('month', 60 * 60 * 24 * 30), | |
('day', 60 * 60 * 24), | |
('hour', 60 * 60), | |
('minute', 60), | |
('second', 1), | |
('milli_second', 1 / 10 ** 3), | |
('micro_second', 1 / 10 ** 6), | |
('nano_second', 1 / 10 ** 9), | |
] | |
strings = [] | |
for period_name, period_seconds in periods: | |
if seconds >= period_seconds: | |
period_value, seconds = divmod(seconds, period_seconds) | |
has_s = 's' if period_value > 1 else '' | |
strings.append("%s %s%s" % (period_value, period_name, has_s)) | |
return ", ".join(strings) | |
print(humanize_time_delta(65213662.010002045)) | |
# 2.0 years, 24.0 days, 18.0 hours, 54.0 minutes, 22.0 seconds, 10.0 milli_seconds, 2.0 micro_seconds, 46.0 nano_seconds |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment