2010-09-12 10 views
15

deniyorum ile Böl timedelta bir sunucu çalışma süresini hesaplamak için birbirleriyle bir timedelta nesneyi bölmek için:Python 2.6.5: 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' 

Bu has been solved in Python 3.2 biliyorum ama idare için uygun bir yol var Python'un önceki sürümlerinde, mikrosaniye sayısını, saniyeleri ve günleri hesaplamak ve bölmek dışında?

sayesinde

Adam Python

+0

olası yinelenen [Python bir datetime.timedelta üzerinde Divisónde gerçekleştirebilirsiniz Nasıl?] (http://stackoverflow.com/questions/865618/how-can-i-perform-divison-on-a-datetime- timedelta-in-python) –

cevap

28

≥2.7, a .total_seconds() method timedelta içerdiği toplam saniye hesaplamak için vardır: Aksi

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

, hesaplamak etmekten başka yol yoktur toplam mikro saniye (sürüm < 2.7 için)

>>> 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 Harika, ama 2.6'mda çalışmayacaktı. –

+4

@Adam: İkinci yöntem 2.6'da çalışıyor. (Tabii ki "çözümden" sadece budur.) – kennytm

+0

İkinci yöntem benim için çalıştı, teşekkürler! –