Python 2.6.5:用timedelta划分timedelta [英] Python 2.6.5: Divide timedelta with timedelta

查看:99
本文介绍了Python 2.6.5:用timedelta划分timedelta的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个 timedelta 对象与另一个对象相除,以计算服务器正常运行时间:

I'm trying to divide one timedelta object with another to calculate a server uptime:

>>> 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≥2.7中,有一种 .total_seconds()方法来计算总数timedelta中包含的秒数:

In Python ≥2.7, there is a .total_seconds() method to compute the total seconds contained in the timedelta:

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

否则,没有而是计算总的微秒数(对于版本 <2.7

Otherwise, there is no way but to compute the total microseconds (for versions < 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:用timedelta划分timedelta的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆