开发者

Parsing hh:mm in Python

开发者 https://www.devze.com 2023-03-22 18:54 出处:网络
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.

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 stan开发者_如何学JAVAdard lib that does this?


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


Other than the following, string parsing (or if you want to be even slower for something so simple, use the re module) is the only way I can think of if you rely on the standard library. TimeDelta doesn't seem to suit the task.

>>> import time
>>> x = "02:40"
>>> t = time.strptime(x, "%H:%M")
>>> minutes = t.tm_hour * 60 + t.tm_min
>>> minutes
160


See http://webcache.googleusercontent.com/search?q=cache:EAuL4vECPBEJ:docs.python.org/library/datetime.html+python+datetime&hl=en&client=firefox-a&gl=us&strip=1 since the main Python site is having problems.

The function you want is datetime.strptime or time.strptime, which create either a datetime or time object from a string with a time and another string describing the format.

If you want to not have to describe the format, use dateutil, http://labix.org/python-dateutil.

from dateutil.parser import parse
>>> d = parse('2009/05/13 19:19:30 -0400')
>>> d
datetime.datetime(2009, 5, 13, 19, 19, 30, tzinfo=tzoffset(None, -14400))

See How to parse dates with -0400 timezone string in python?


>>> sum(map(lambda x, y: x * y, map(int, "2:40".split(":")), [60, 1]))
160


I'm sure you can represent the given time as a TimeDelta object. From there I am sure there is an easy way to represent the TimeDelta in minutes.


There is:

from time import strptime
from calendar import timegm

T = '02:40'
t = timegm(strptime('19700101'+T,'%Y%m%d%H:%M'))
print t

But is this really better than brute calculus ?

.

An exotic solution, that doesn't need importing functions :

T = '02:40'
exec('x = %s' % T.replace(':','*60+'))
print x

edit: corrected second solution to obtain minutes, not seconds

.

Simplest solution

T = '02:40'

print int(T[0:2])*60 + int(T[3:])
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号