Hannah
Hannah

Reputation: 2845

Time to decimal time in Python

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.

Upvotes: 18

Views: 69004

Answers (3)

Pierre GM
Pierre GM

Reputation: 20359

Using the datetime module:

>>> t = datetime.time(12,31,53)
>>> ts = t.hour * 3600 + t.minute * 60 + t.second
>>> print ts
45113

Upvotes: 4

Glyph
Glyph

Reputation: 31910

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')

Upvotes: 14

stepancheg
stepancheg

Reputation: 4276

t = "1:12:23"
(h, m, s) = t.split(':')
result = int(h) * 3600 + int(m) * 60 + int(s)

Upvotes: 24

Related Questions