2010-06-23 65 views
6

我應該使用哪種Python日期時間或時間方法將HH:MM:SS中的時間轉換爲小數時間(秒)?時間表示持續時間(大部分時間不到一分鐘),並且沒有與日期相關聯。Python中十進制時間的時間

回答

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

如果「十進制時間」你的意思是秒的整數倍,那麼你可能想使用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 

(如果你真的想要一個Decimal,當然,它很容易到那裏...)

>>> import decimal 
>>> decimal.Decimal(x.seconds) 
Decimal('8954') 
+0

但是n.b.如果存在微秒組件,則會截斷它。 – 2016-05-02 18:37:30

0

使用datetime模塊:

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