Skip to content

Instantly share code, notes, and snippets.

@gokart23
Created December 20, 2017 07:27
Show Gist options
  • Save gokart23/76725ffb0669b7e578e49234d5a2e64a to your computer and use it in GitHub Desktop.
Save gokart23/76725ffb0669b7e578e49234d5a2e64a to your computer and use it in GitHub Desktop.
Convert human-readable time ('1 min 3 sec', '0.58 hr', etc) to milliseconds
interval_dict = OrderedDict([
('hr', 3600*1000),
('min', 60*1000),
('sec', 1000),
('ms' , 1),
])
def convert_to_ms(string):
interval_regex = re.compile( "^[<]?(?P<value>(\d\.)?[0-9]+) (?P<unit>({0}))".format("|".join(interval_dict.keys())) )
milliseconds = 0
while string:
match = interval_regex.match(string)
if match:
value, unit = float(match.group("value")), match.group("unit")
if value == 0:
return milliseconds
if float(value) and unit in interval_dict:
milliseconds += int(value * interval_dict[unit])
string = string[match.end():].strip()
else:
raise Exception("Not a float value '{0}', or unable to find interval '{1}' for string '{2}'".format(value, unit, string))
else:
print "WARN:Unable to match string '{0}'".format(string)
return -1.0
return milliseconds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment