18

我正在尝试将一个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'

我知道这已经在 Python 3.2 中解决了,但是除了计算微秒数、秒数和天数以及除法之外,在 Python 的早期版本中是否有一种方便的方法来处理它?

谢谢,

亚当

4

1 回答 1

33

在 Python ≥2.7 中,有一种.total_seconds()方法可以计算 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
于 2010-09-12T12:51:20.247 回答