Created
March 14, 2019 16:20
-
-
Save andr1an/75e11f9d54688f8fcc272c2ca441583b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
_RE_HMS = re.compile( | |
r'^\s*(?:(?P<h>\d+)h)?\s*(?:(?P<m>\d+)m)?\s*(?:(?P<s>\d+)s?)?\s*$') | |
def to_hms(seconds): | |
"""Converts seconds (int) to "h m s" (str).""" | |
minutes, seconds = divmod(seconds, 60) | |
hours, minutes = divmod(minutes, 60) | |
_format = '' | |
if seconds: | |
_format = '{seconds}s' | |
if minutes: | |
_format = '{minutes}m' + (' ' + _format if _format else _format) | |
if hours: | |
_format = '{hours}h' + (' ' + _format if _format else _format) | |
return _format.format(hours=hours, minutes=minutes, seconds=seconds) | |
def from_hms(hms_string): | |
"""Converts "h m s" (str) to seconds (int).""" | |
match_hms = _RE_HMS.match(str(hms_string)) | |
if not match_hms: | |
raise ValueError('"{}" is not a valid time!'.format(hms_string)) | |
hms_multipliers = {k: int(match_hms.group(k)) | |
if match_hms.group(k) is not None else 0 | |
for k in 'hms'} | |
return (hms_multipliers['h'] * 3600 + | |
hms_multipliers['m'] * 60 + | |
hms_multipliers['s']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment