I’m writing a function that needs to parse string to a timedelta
. The user must enter something like "32m"
or "2h32m"
, or even "4:13"
or "5hr34m56s"
… Is there a library or something that has this sort of thing already implemented?
Advertisement
Answer
For the first format (5hr34m56s
), you should parse using regular expressions
Here is re-based solution:
import re from datetime import timedelta regex = re.compile(r'((?P<hours>d+?)hr)?((?P<minutes>d+?)m)?((?P<seconds>d+?)s)?') def parse_time(time_str): parts = regex.match(time_str) if not parts: return parts = parts.groupdict() time_params = {} for name, param in parts.items(): if param: time_params[name] = int(param) return timedelta(**time_params) >>> from parse_time import parse_time >>> parse_time('12hr') datetime.timedelta(0, 43200) >>> parse_time('12hr5m10s') datetime.timedelta(0, 43510) >>> parse_time('12hr10s') datetime.timedelta(0, 43210) >>> parse_time('10s') datetime.timedelta(0, 10) >>>