Ada*_*tan 16 python division 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'
Run Code Online (Sandbox Code Playgroud)
我知道这已经在Python 3.2中得到了解决,但除了计算微秒,秒和天数以及除以?之外,还有一种方便的方法可以在Python的早期版本中处理它吗?
谢谢,
亚当
ken*_*ytm 31
在Python≥2.7中,有一种.total_seconds()方法可以计算timedelta中包含的总秒数:
>>> down_time.total_seconds() / server_life_period.total_seconds()
0.0003779903727652387
Run Code Online (Sandbox Code Playgroud)
否则,除了计算总微秒数(版本<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
Run Code Online (Sandbox Code Playgroud)