Converting time period strings to value/unit pair

Posted by randomtoor on Stack Overflow See other posts from Stack Overflow or by randomtoor
Published on 2012-09-06T15:26:13Z Indexed on 2012/09/06 15:38 UTC
Read the original article Hit count: 123

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about python

Related posts about regex