Skip to content

Instantly share code, notes, and snippets.

@dcwatson
Created July 12, 2021 16:13
Show Gist options
  • Save dcwatson/fe7851fb01a89cd0efd872b3dd592b29 to your computer and use it in GitHub Desktop.
Save dcwatson/fe7851fb01a89cd0efd872b3dd592b29 to your computer and use it in GitHub Desktop.
Convert between duration strings and Python timedelta objects
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