From efbc1c44bb3ef68c90dc8cbdf25e3908a2753f9f Mon Sep 17 00:00:00 2001 From: Ethan Dalool Date: Mon, 6 Jan 2020 22:18:50 -0800 Subject: [PATCH] Add hms.py. --- voussoirkit/hms.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 voussoirkit/hms.py diff --git a/voussoirkit/hms.py b/voussoirkit/hms.py new file mode 100644 index 0000000..47a2f7f --- /dev/null +++ b/voussoirkit/hms.py @@ -0,0 +1,36 @@ +import math + +def hms_to_seconds(hms): + ''' + Convert hh:mm:ss string to an integer seconds. + ''' + parts = hms.split(':') + seconds = 0 + if len(parts) > 3: + raise ValueError(f'{hms} doesn\'t match the HH:MM:SS format.') + if len(parts) == 3: + seconds += int(parts[0]) * 3600 + parts.pop(0) + if len(parts) == 2: + seconds += int(parts[0]) * 60 + parts.pop(0) + if len(parts) == 1: + seconds += float(parts[0]) + return seconds + +def seconds_to_hms(seconds): + ''' + Convert integer number of seconds to an hh:mm:ss string. + Only the necessary fields are used. + ''' + seconds = math.ceil(seconds) + (minutes, seconds) = divmod(seconds, 60) + (hours, minutes) = divmod(minutes, 60) + parts = [] + if hours: + parts.append(hours) + if hours or minutes: + parts.append(minutes) + parts.append(seconds) + hms = ':'.join(f'{part:02d}' for part in parts) + return hms