Which Python datetime or time method should I use to convert time in HH:MM:SS to decimal time in seconds? The times represent durations of time (most are less than a minute) and are not connected to a date.
+2
A:
t = "1:12:23"
(h, m, s) = t.split(':')
result = int(h) * 3600 + int(m) * 60 + int(s)
stepancheg
2010-06-23 01:12:21
+2
A:
If by "decimal time" you mean an integer number of seconds, then you probably want to use datetime.timedelta
:
>>> import datetime
>>> hhmmss = '02:29:14'
>>> [hours, minutes, seconds] = [int(x) for x in hhmmss.split(':')]
>>> x = datetime.timedelta(hours=hours, minutes=minutes, seconds=seconds)
>>> x
datetime.timedelta(0, 8954)
>>> x.seconds
8954
(If you actually wanted a Decimal
, of course, it's easy enough to get there...)
>>> import decimal
>>> decimal.Decimal(x.seconds)
Decimal('8954')
Glyph
2010-06-23 01:13:54