Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time to decimal time in Python

Tags:

python

time

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.

like image 203
Hannah Avatar asked Jun 23 '10 01:06

Hannah


3 Answers

t = "1:12:23"
(h, m, s) = t.split(':')
result = int(h) * 3600 + int(m) * 60 + int(s)
like image 57
stepancheg Avatar answered Oct 10 '22 03:10

stepancheg


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')
like image 23
Glyph Avatar answered Oct 10 '22 04:10

Glyph


Using the datetime module:

>>> t = datetime.time(12,31,53)
>>> ts = t.hour * 3600 + t.minute * 60 + t.second
>>> print ts
45113
like image 21
Pierre GM Avatar answered Oct 10 '22 02:10

Pierre GM