From 09faa8e6fdb1ca5345742fb70763314a6ecd055b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Kucharczyk?= Date: Fri, 10 Nov 2023 20:07:41 +0100 Subject: [PATCH] Fix edge case in format_duration Fixes #65 ```python def test_specific_precise_if_unncessary(self): delta = timedelta(hours=2, minutes=40) result = format_duration(delta, "%02.0H:%02.0m") self.assertEqual(result, "02:40") ``` This test fails by returning "03:40" instead. The problem is in the way `format_duration` handles fractional hours. To fix it, we need to switch between using hours and fractional hours depending on if minutes are present in the formatted string. --- common/time.py | 4 ++-- tests/test_time.py | 10 ++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/common/time.py b/common/time.py index c37f67b..be09c1f 100644 --- a/common/time.py +++ b/common/time.py @@ -44,7 +44,7 @@ def format_duration( # timestamps where end is before start if seconds_total < 0: seconds_total = 0 - days = hours = minutes = seconds = 0 + days = hours = hours_float = minutes = seconds = 0 remainder = seconds = seconds_total if "%d" in format_string: days, remainder = divmod(seconds_total, day_seconds) @@ -55,7 +55,7 @@ def format_duration( minutes, seconds = divmod(remainder, minute_seconds) literals = { "d": str(days), - "H": str(hours), + "H": str(hours) if "m" not in format_string else str(hours_float), "m": str(minutes), "s": str(seconds), "r": str(seconds_total), diff --git a/tests/test_time.py b/tests/test_time.py index 860475c..e910d7b 100644 --- a/tests/test_time.py +++ b/tests/test_time.py @@ -83,6 +83,16 @@ class FormatDurationTest(unittest.TestCase): result = format_duration(delta, "%r seconds") self.assertEqual(result, "0 seconds") + def test_specific(self): + delta = timedelta(hours=2, minutes=40) + result = format_duration(delta, "%H:%m") + self.assertEqual(result, "2:40") + + def test_specific_precise_if_unncessary(self): + delta = timedelta(hours=2, minutes=40) + result = format_duration(delta, "%02.0H:%02.0m") + self.assertEqual(result, "02:40") + def test_all_at_once(self): delta = timedelta(days=50, hours=10, minutes=34, seconds=24) result = format_duration(