Converting time period strings to value/unit pair
- by randomtoor
I need to parse the contents of a string that represents a time period. The format of the string is value/unit, e.g.: 1s, 60min, 24h. I would separate the actual value (an int) and unit (a str) to separated variables.
At the moment I do it like this:
def validate_time(time):
binsize = time.strip()
unit = re.sub('[0-9]','',binsize)
if unit not in ['s','m','min','h','l']:
print "Error: unit {0} is not valid".format(unit)
sys.exit(2)
tmp = re.sub('[^0-9]','',binsize)
try:
value = int(tmp)
except ValueError:
print "Error: {0} is not valid".format(time)
sys.exit(2)
return value,unit
However, it is not ideal as things like 1m0 are also (wrongly) validated (value=10,unit=m).
What is the best way to validate/parse this input?