function to convert degree (hour), minute, seconds string to integer
Paul McGuire
ptmcg at austin.rr._bogus_.com
Thu Jul 27 11:54:07 EDT 2006
<google0 at lazytwinacres.net> wrote in message
news:1153967597.980549.6940 at h48g2000cwc.googlegroups.com...
> 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)
More information about the Python-list
mailing list