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.
t = "1:12:23"
(h, m, s) = t.split(':')
result = int(h) * 3600 + int(m) * 60 + int(s)
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')
Using the datetime
module:
>>> t = datetime.time(12,31,53)
>>> ts = t.hour * 3600 + t.minute * 60 + t.second
>>> print ts
45113
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With