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?
Personally, I think simply parsing the string is far easier to read:
Note that using negative indexing means it will handle strings without the leading zero on the hour:
You could also use the
split()function:Or use the
map()function to convert the pieces to integers:Speed
Using the
timeitmodule indicates it is also faster than other methods proposed here:The
split()method is a bit slower:And using
map()a bit slower again:John Machin’s map and sum is about 2.4 times slower:
Chrono Kitsune’s
strptime()-based answer is ten times slower: