我正在尝试将一个 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版本中,除了计算微秒数、秒数和天数以及除法之外,有没有方便的方法来处理呢?
谢谢,
亚当
最佳答案
在 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
关于Python 2.6.5 : Divide timedelta with timedelta,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3694835/