Last active
December 10, 2020 08:42
-
-
Save kemingy/76c85d3c6658ea1b8180dea83a9a896b to your computer and use it in GitHub Desktop.
python argparser customized duration type
This file contains hidden or 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
| 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