Python 2.6.5:用timedelta除timedelta

19 投票
1 回答
16110 浏览
提问于 2025-04-16 04:02

我正在尝试用一个 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 版本中,有没有什么方便的方法来处理这个问题,除了计算微秒、秒和天数然后进行除法?

谢谢,

亚当

1 个回答

34

在Python 2.7及以上版本中,有一个叫做.total_seconds()的方法,可以用来计算时间差中包含的总秒数。

>>> 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

撰写回答