python 31 lines · 8 steps

Parsing duration strings like 1h30m in Python

A regex scanner turns compact duration strings into a total number of seconds while rejecting malformed input.

Explained by highlit
1import re
2 
3_UNIT_SECONDS = {
4 "w": 604800,
5 "d": 86400,
6 "h": 3600,
7 "m": 60,
8 "s": 1,
9}
10 
11_TOKEN = re.compile(r"(\d+)([wdhms])")
12 
13 
14def parse_duration(value: str) -> int:
15 text = value.strip().lower()
16 if not text:
17 raise ValueError("empty duration string")
18 
19 pos = 0
20 total = 0
21 for match in _TOKEN.finditer(text):
22 if match.start() != pos:
23 raise ValueError(f"unexpected token near {text[pos:]!r}")
24 amount, unit = match.groups()
25 total += int(amount) * _UNIT_SECONDS[unit]
26 pos = match.end()
27 
28 if pos != len(text):
29 raise ValueError(f"invalid duration: {value!r}")
30 
31 return total
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A lookup table maps units to a common base so each token contributes cleanly to one total.
  2. 2Tracking the match position lets a regex scanner detect gaps and reject unexpected characters.
  3. 3Validating that the scan reached the end of the string catches trailing junk the pattern skipped.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Parsing duration strings like 1h30m in Python — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code