Personally, I find that just parsing a string is much easier to read:
>>> s = '02:40' >>> int(s[:-3]) * 60 + int(s[-2:]) 160
Note that using negative indexing means that it will process rows without a leading zero per hour:
>>> s = '2:40' >>> int(s[:-3]) * 60 + int(s[-2:]) 160
You can also use the split() function:
>>> hours, minutes = s.split(':') >>> int(hours) * 60 + int(minutes) 160
Or use the map() function to convert shapes to integers:
>>> hours, minutes = map(int, s.split(':')) >>> hours * 60 + minutes 160
Speed
Using the timeit module indicates that it is also faster than the other methods suggested here:
>>> import timeit >>> parsetime = timeit.timeit("mins = int(s[:-3]) * 60 + int(s[-2:])", "s='02:40'", number=100000) / 100000 >>> parsetime 9.018449783325196e-06
The split() method is a bit slower:
>>> splittime = timeit.timeit("hours,minutes = s.split(':'); mins=int(hours)*60 + int(minutes)", "s='02:40'", number=100000)/100000 >>> splittime 1.1217889785766602e-05 >>> splittime/parsetime 1.2438822697120402
And again using map() little slower:
>>> splitmaptime = timeit.timeit("hours,minutes = map(int, s.split(':')); mins=hours*60 + minutes", "s='02:40'", number=100000)/100000 >>> splitmaptime 1.3971350193023682e-05 >>> splitmaptime/parsetime 1.5491964282881776
John Machin's card and amount are about 2.4 times slower:
>>> summaptime = timeit.timeit('mins=sum(map(lambda x, y: x * y, map(int, "2:40".split(":")), [60, 1]))', "s='02:40'", number=100000) / 100000 >>> summaptime 2.1276121139526366e-05 >>> summaptime/parsetime 2.43
The answer to Chrono Kitsune strptime() is ten times slower:
>>> strp = timeit.timeit("t=time.strptime(s, '%H:%M');mins=t.tm_hour * 60 + t.tm_min", "import time; s='02:40'", number=100000)/100000 >>> strp 9.0362770557403569e-05 >>> strp/parsetime 10.019767557444432