From 4e67735de8c5d877d32bbd3f9894442d07fcafbf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Kucharczyk?= Date: Thu, 5 Jan 2023 17:13:45 +0100 Subject: [PATCH] Fix negative playtimes being considered positive --- CHANGELOG.md | 1 + src/web/common/util/time.py | 3 +++ tests/test_time.py | 5 +++++ 3 files changed, 9 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1aaf77d..c7101a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,5 @@ ## Unreleased +* Fix negative playtimes being considered positive * Add %d for days to common.util.time.format_duration * Set up tests, add tests for common.util.time * Display total hours played on homepage diff --git a/src/web/common/util/time.py b/src/web/common/util/time.py index 82b7ff4..f707f86 100644 --- a/src/web/common/util/time.py +++ b/src/web/common/util/time.py @@ -23,6 +23,9 @@ def format_duration( hour_seconds = 60 * minute_seconds day_seconds = 24 * hour_seconds seconds_total = int(duration.total_seconds()) + # timestamps where end is before start + if seconds_total < 0: + seconds_total = 0 days, remainder = divmod(seconds_total, day_seconds) hours, remainder = divmod(remainder, hour_seconds) minutes, seconds = divmod(remainder, minute_seconds) diff --git a/tests/test_time.py b/tests/test_time.py index 53a74f4..98b713c 100644 --- a/tests/test_time.py +++ b/tests/test_time.py @@ -51,3 +51,8 @@ class FormatDurationTest(unittest.TestCase): self.assertEqual( result, "50 days, 10 hours, 34 minutes, 24 seconds, 4358064 total seconds" ) + + def test_negative(self): + delta = timedelta(hours=-2) + result = format_duration(delta, "%H hours") + self.assertEqual(result, "0 hours")