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.
3 Answers
10
votes
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')