【问题标题】:Percentages in timedelta objects in Python?Python中timedelta对象的百分比?
【发布时间】:2013-05-26 08:36:55
【问题描述】:

我正在开发一个高级计时和时间统计应用程序。我正在使用 Python timedelta 对象来表示应用程序中的时间跨度。

我想弄清楚是否有办法表示 timedelta 对象的任意部分。

为 timedelta 提供的运算符只允许使用整数。您可以将 timedelta 乘以一个整数,也可以将其除以一个整数,但浮点数都不能。

我希望能够做两件事:

1:给定一个 timedelta 对象,找出它的任意百分比。换句话说,乘法或除法的能力:

from datetime import timedelta
import math
td = timedelta(1)
newTd = td * 0.01 # 1% of the time delta specified in td
newTd = td * 1.04 # 104% of the time delta given in td
newTd = td * math.pi # the timedelta multiplied by pi (lol) 

2:给定两个 timedelta 对象,计算一个 timedelta 给出的时间跨度相对于另一个 time delta 作为浮点数的百分比:

from datetime import timedelta
td1 = timedelta(1)
td2 = timedelta(2)
td1 / td2 # should give me 0.5
td2 = timedelta(days=4, minutes=50)
td1 / td2 # not sure what this would result in, but, the percentage of time 1 day fills out of 4 days and 50 minutes of time

这两个都要求我能够使用浮点数对 timedelta 对象进行操作。我不确定这是否可以做到。那么,能不能做到,如果不能,有没有更好的替代方案呢?

【问题讨论】:

    标签: python datetime timedelta


    【解决方案1】:

    您可以从timedelta.total_seconds() 获取秒数并使用它。

    >>> from datetime import timedelta
    >>> td1 = timedelta(1)
    >>> td2 = timedelta(2)
    >>> td1.total_seconds() / td2.total_seconds() # should give me 0.5
    0.5
    >>> td2 = timedelta(days=4, minutes=50)
    >>> td1.total_seconds() / td2.total_seconds()
    0.24784853700516352
    

    【讨论】:

    • 在python3中,您可以使用浮点数直接对timedelta对象进行操作,也可以将两个timedelta对象相除得到一个浮点数。
    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2012-04-18
    • 2018-04-18
    • 2018-03-29
    • 2019-05-15
    • 2015-12-17
    相关资源
    最近更新 更多