Python 2.6.5:将 timedelta 除以 timedelta

发布于 2024-09-19 17:43:45 字数 728 浏览 3 评论 0原文

我正在尝试将一个 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的早期版本中,除了计算微秒数、秒数和天数以及除法之外,是否有方便的方法来处理它?

谢谢,

亚当

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'

I know this has been solved in Python 3.2, but is there a convenient way to handle it in prior versions of Python, apart from calculating the number of microseconds, seconds and days and dividing?

Thanks,

Adam

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

余生一个溪 2024-09-26 17:43:45

在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

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文