Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing hh:mm in Python

Sometimes I get a string like "02:40" indicating 2 hours and 40 minutes. I'd like to parse that string into the number of minutes (160 in this case) using Python.

Sure, I can parse the string and multiply the hours by 60, but is there something in the standard lib that does this?

like image 497
Ram Rachum Avatar asked Jul 24 '11 16:07

Ram Rachum


1 Answers

Personally, I think simply parsing the string is far easier to read:

>>> s = '02:40'
>>> int(s[:-3]) * 60 + int(s[-2:])
160

Note that using negative indexing means it will handle strings without the leading zero on the hour:

>>> s = '2:40'
>>> int(s[:-3]) * 60 + int(s[-2:])
160

You could also use the split() function:

>>> hours, minutes = s.split(':')
>>> int(hours) * 60 + int(minutes)
160

Or use the map() function to convert the pieces to integers:

>>> hours, minutes = map(int, s.split(':'))
>>> hours * 60 + minutes
160

Speed

Using the timeit module indicates it is also faster than other methods proposed 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 using map() a bit slower again:

>>> 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 map and sum is 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

Chrono Kitsune's strptime()-based answer 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
like image 113
Blair Avatar answered Nov 15 '22 06:11

Blair