Here are some examples of what the time strings would look like:
parse_time_string("20s") # 20
parse_time_string("30sec") # 30
parse_time_string("3m") # 180
parse_time_string("2min") # 120
parse_time_string("5h") # 18000
parse_time_string("1d") # 86400
>Solution :
A simple approach using a regexp to split the string to the number and unit parts, and a bit of multiplication:
import re
multipliers = {
"s": 1,
"sec": 1,
"m": 60,
"min": 60,
"h": 60 * 60,
"d": 86400,
}
def parse_time_string(param):
value, unit = re.match(r"^(\d+)([a-z]+)$", param).groups()
return int(value) * multipliers[unit]
for example in ("20s", "30sec", "3m", "2min", "5h", "1d"):
print(example, parse_time_string(example))
20s 20
30sec 30
3m 180
2min 120
5h 18000
1d 86400