Add hms_letters functions to make 00h00m00s outputs.

This commit is contained in:
voussoir 2021-12-21 17:09:40 -08:00
parent 9381c2c9c7
commit 597705fc57
No known key found for this signature in database
GPG key ID: 5F7554F8C26DACCB

View file

@ -1,4 +1,5 @@
import math
import re
import sys
from voussoirkit import pipeable
@ -21,6 +22,18 @@ def hms_to_seconds(hms) -> float:
seconds += float(parts[0])
return seconds
def hms_letters_to_seconds(hms) -> float:
match = re.match(r'(?:(\d+)h)?(?:(\d+)m)?(\d+)s?', hms.strip())
if not match:
raise ValueError(f'{hms} does not match 00h00m00s pattern')
(hours, minutes, seconds) = match.groups()
seconds = int(seconds)
if hours:
seconds += int(hours) * 3600
if minutes:
seconds += int(minutes) * 60
return seconds
def seconds_to_hms(seconds, force_minutes=False, force_hours=False) -> str:
'''
Convert integer number of seconds to an hh:mm:ss string.
@ -38,11 +51,26 @@ def seconds_to_hms(seconds, force_minutes=False, force_hours=False) -> str:
hms = ':'.join(f'{part:02d}' for part in parts)
return hms
def seconds_to_hms_letters(seconds, force_minutes=False, force_hours=False) -> str:
seconds = math.ceil(seconds)
(minutes, seconds) = divmod(seconds, 60)
(hours, minutes) = divmod(minutes, 60)
parts = []
if hours or force_hours:
parts.append(f'{hours:02d}h')
if hours or minutes or force_hours or force_minutes:
parts.append(f'{minutes:02d}m')
parts.append(f'{seconds:02d}s')
hms = ''.join(parts)
return hms
def main(args):
lines = pipeable.input_many(args, strip=True, skip_blank=True)
for line in lines:
if ':' in line:
line = hms_to_seconds(line)
if 's' in line:
line = hms_letters_to_seconds(line)
else:
line = float(line)
if line > 60: