Skip to content

Instantly share code, notes, and snippets.

@kemingy
Last active December 10, 2020 08:42
Show Gist options
  • Select an option

  • Save kemingy/76c85d3c6658ea1b8180dea83a9a896b to your computer and use it in GitHub Desktop.

Select an option

Save kemingy/76c85d3c6658ea1b8180dea83a9a896b to your computer and use it in GitHub Desktop.
python argparser customized duration type
def duration_to_seconds(duration: str):
"""convert duration string to seconds"""
unit_to_seconds = {
"ns": 1e-9,
"µs": 1e-6,
"ms": 1e-3,
"s": 1,
"m": 60,
"h": 3600,
}
unit = "".join(char for char in duration if char.isalpha()).lower()
value = float(duration.rstrip(unit))
if unit not in unit_to_seconds or not duration.endswith(unit):
raise ValueError(f"cannot parse {duration} as time duration")
return value * unit_to_seconds[unit]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment