Python 2.6.5:用timedelta划分timedelta

编程入门 行业动态 更新时间:2024-10-26 20:32:50
本文介绍了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

本文发布于:2023-11-22 03:10:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615750.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Python   timedelta

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!