Skip to content

Instantly share code, notes, and snippets.

@Synthetica9
Created June 11, 2021 11:49
Show Gist options
  • Save Synthetica9/396047ec3ef3133a5015cea20ef1b030 to your computer and use it in GitHub Desktop.
Save Synthetica9/396047ec3ef3133a5015cea20ef1b030 to your computer and use it in GitHub Desktop.
from datetime import timedelta
import re
def parseTime(s):
m = re.match(r'^(\d+) *([a-z]+)$', s)
if m is None:
raise ValueError("couldn't parse time string")
units = 'seconds minutes hours days weeks'.split()
num = float(m[1])
for unit in units:
if unit.startswith(m[2]):
break
else:
raise ValueError(f'Unknown unit {m[2]}')
return timedelta(**{unit: num})
print(parseTime('1d'))
print(parseTime('5m'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment