<[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > I know this is a trivial function, and I've now spent more time > searching for a surely-already-reinvented wheel than it would take to > reinvent it again, but just in case... is there a published, > open-source, function out there that takes a string in the form of > "hh:mm:ss" (where hh is 00-23, mm is 00-59, and ss is 00-59) and > converts it to an integer (ss + 60 * (mm + 60 * hh))? I'd like > something that throws an exception if hh, mm, or ss is out of range, or > perhaps does something "reasonable" (like convert "01:99" to 159). > Thanks, > --dang
In a froth of functionalism, here is my submission. -- Paul tests = """\ 00:00:00 01:01:01 23:59:59 24:00:00 H1:00:00 12:34:56.789""".split("\n") def time2secs(t,decimal=False): if decimal: tflds = map(float,t.split(":")) else: tflds = map(int,t.split(".")[0].split(":")) nomorethan = lambda (a,maxa) : 0 <= a < maxa if sum(map(nomorethan, zip(tflds,(24,60,60)))) == len(tflds): return reduce(lambda a,b: a*60+b, tflds) else: raise ValueError("invalid time field value in '%s'" % str(t)) for tt in tests: try: print time2secs(tt) print time2secs(tt,True) except Exception,e: print "%s: %s" % (e.__class__.__name__, e) -- http://mail.python.org/mailman/listinfo/python-list