2010-09-12 59 views
15

我試圖將一個timedelta對象與另一個計算服務器正常運行時間:的Python 2.6.5:除以timedelta與timedelta

>>> import datetime 
>>> installation_date=datetime.datetime(2010,8,01) 
>>> down_time=datetime.timedelta(seconds=1400) 
>>> server_life_period=datetime.datetime.now()-installation_date 
>>> down_time_percentage=down_time/server_life_period 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: unsupported operand type(s) for /: 'datetime.timedelta' 
      and 'datetime.timedelta' 

我知道這has been solved in Python 3.2,但有來處理它的便捷方法在以前的Python版本中,除了計算微秒,秒和天的數量和分割?

感謝,

亞當

+0

可能的重複[如何在python的datetime.timedelta上執行divison?](http://stackoverflow.com/questions/865618/how-can-i-perform-divison-on-a-datetime- timedelta-in-python) – 2012-09-13 14:37:58

回答

28

在Python≥2.7,有a .total_seconds() method計算包含在timedelta總秒:

>>> down_time.total_seconds()/server_life_period.total_seconds() 
0.0003779903727652387 

否則,沒有辦法,只能計算總微秒(對於版本< 2.7

>>> def get_total_seconds(td): return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 1e6)/1e6 
... 
>>> get_total_seconds(down_time)/get_total_seconds(server_life_period) 
0.0003779903727652387 
+0

+1很好,但它不適用於我的2.6。 – 2010-09-12 13:08:49

+4

@Adam:第二種方法適用於2.6。 (當然這只是「除了」解決方案。) – kennytm 2010-09-12 13:20:03

+0

第二種方法適用於我,謝謝! – 2014-10-16 13:48:31