Commit f8ea4ada authored by Michael Hanselmann's avatar Michael Hanselmann
Browse files

utils: Add function to format seconds

Signed-off-by: default avatarMichael Hanselmann <>
Reviewed-by: default avatarIustin Pop <>
parent 0fb44e89
......@@ -3188,6 +3188,31 @@ def FormatTime(val):
return time.strftime("%F %T", time.localtime(val))
def FormatSeconds(secs):
"""Formats seconds for easier reading.
@type secs: number
@param secs: Number of seconds
@rtype: string
@return: Formatted seconds (e.g. "2d 9h 19m 49s")
parts = []
secs = round(secs, 0)
if secs > 0:
# Negative values would be a bit tricky
for unit, one in [("d", 24 * 60 * 60), ("h", 60 * 60), ("m", 60)]:
(complete, secs) = divmod(secs, one)
if complete or parts:
parts.append("%d%s" % (complete, unit))
parts.append("%ds" % secs)
return " ".join(parts)
def ReadWatcherPauseFile(filename, now=None, remove_after=3600):
"""Reads the watcher pause file.
......@@ -2364,5 +2364,27 @@ class TestEnsureDirs(unittest.TestCase):
class TestFormatSeconds(unittest.TestCase):
def test(self):
self.assertEqual(utils.FormatSeconds(1), "1s")
self.assertEqual(utils.FormatSeconds(3600), "1h 0m 0s")
self.assertEqual(utils.FormatSeconds(3599), "59m 59s")
self.assertEqual(utils.FormatSeconds(7200), "2h 0m 0s")
self.assertEqual(utils.FormatSeconds(7201), "2h 0m 1s")
self.assertEqual(utils.FormatSeconds(7281), "2h 1m 21s")
self.assertEqual(utils.FormatSeconds(29119), "8h 5m 19s")
self.assertEqual(utils.FormatSeconds(19431228), "224d 21h 33m 48s")
self.assertEqual(utils.FormatSeconds(-1), "-1s")
self.assertEqual(utils.FormatSeconds(-282), "-282s")
self.assertEqual(utils.FormatSeconds(-29119), "-29119s")
def testFloat(self):
self.assertEqual(utils.FormatSeconds(1.3), "1s")
self.assertEqual(utils.FormatSeconds(1.9), "2s")
self.assertEqual(utils.FormatSeconds(3912.12311), "1h 5m 12s")
self.assertEqual(utils.FormatSeconds(3912.8), "1h 5m 13s")
if __name__ == '__main__':
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment