From fdb9aa8e84bc4e8e1391a32f0d50ef28be9db87d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Kucharczyk?= Date: Thu, 5 Jan 2023 11:14:00 +0100 Subject: [PATCH] Add format_duration to common.util.time --- CHANGELOG.md | 1 + src/web/common/util/time.py | 39 ++++++++++++++++++++++++++++++++++++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 55d55ff..2a976fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,5 @@ ## Unreleased +* Add format_duration to common.util.time * Allow deleting sessions * Redirect after adding game/platform/purchase/session * Fix display of duration_manual diff --git a/src/web/common/util/time.py b/src/web/common/util/time.py index 57c8885..13ee8a1 100644 --- a/src/web/common/util/time.py +++ b/src/web/common/util/time.py @@ -1,7 +1,44 @@ -from datetime import datetime +from datetime import datetime, timedelta from django.conf import settings from zoneinfo import ZoneInfo +import re def now(): return datetime.now(ZoneInfo(settings.TIME_ZONE)) + + +def format_duration( + duration: timedelta, format_string: str = "%H hours %m minutes" +) -> str: + """ + Format timedelta into the specified format_string. + If duration is less than 60 seconds, skips formatting, returns "less than a minute". + If duration is 0, skips formatting, returns 0. + Valid format variables: + - %H hours + - %m minutes + - %s seconds + """ + seconds_in_hours = 3600 + seconds_in_minute = 60 + hours: int + minutes: int + seconds: int + seconds_total: int + remainder: int + seconds_total = duration.total_seconds() + if seconds_total == 0: + return 0 + else: + hours = int(seconds_total // seconds_in_hours) + remainder = int(seconds_total % seconds_in_hours) + minutes = int(remainder // seconds_in_minute) + if hours == 0 and minutes == 0: + return "less than a minute" + seconds = int(minutes % seconds_in_minute) + literals = {"%H": str(hours), "%m": str(minutes), "%s": str(seconds)} + formatted_string = format_string + for pattern, replacement in literals.items(): + formatted_string = re.sub(pattern, replacement, formatted_string) + return formatted_string