Created
July 12, 2021 16:13
-
-
Save dcwatson/fe7851fb01a89cd0efd872b3dd592b29 to your computer and use it in GitHub Desktop.
Convert between duration strings and Python timedelta objects
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 | |
from datetime import timedelta | |
format_specs = { | |
"y": 31536000, | |
"w": 604800, | |
"d": 86400, | |
"h": 3600, | |
"m": 60, | |
"s": 1, | |
} | |
format_splitter = re.compile(r"([ydhms])") | |
def to_timedelta(duration: str) -> timedelta: | |
parts = format_splitter.split(duration.lower().strip()) | |
seconds = 0 | |
for pair in zip(parts[::2], parts[1::2]): | |
if pair: | |
seconds += int(pair[0]) * format_specs[pair[1]] | |
return timedelta(seconds=seconds) | |
def to_duration(delta: timedelta) -> str: | |
seconds = delta.total_seconds() | |
duration = [] | |
for fmt, sec in format_specs.items(): | |
num = int(seconds // sec) | |
if num > 0: | |
duration.append("{}{}".format(num, fmt)) | |
seconds -= num * sec | |
return "".join(duration) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment