在Python中使用浮点数乘以Timedelta

21
我有两个日期,可以像平常一样计算时间差。但是我想用计算出的时间差来计算某些百分比。
full_time = (100/percentage) * timdelta

但是看起来它只能与整数相乘。

我该如何使用 float 作为乘数而不是 int

示例:

percentage     = 43.27
passed_time    = fromtimestamp(fileinfo.st_mtime) - fromtimestamp(fileinfo.st_ctime)
multiplier     = 100 / percentage   # 2.3110700254217702796394730760342
full_time      = multiplier * passed_time # BUG: here comes exception
estimated_time = full_time - passed_time

如果使用 int(multiplier) — 精度会降低。


你说得对,timedelta只支持与整数的乘法或除法,但为什么不逐步执行数学运算呢?full_time = passed_time * 100 / int(percentage) - Colin O'Coal
@Colin O'Coal,因为精度问题:2 != 2.3131。比较:571 * 2 = 114219,03(3)分钟);571 * 2.3131 = 1320,780122,0130016(6)分钟)。差异约为3分钟(!) - Крайст
2个回答

28

你可以将其转换为总秒数,然后再转回来:

full_time = timedelta(seconds=multiplier * passed_time.total_seconds())

timedelta.total_seconds从Python 2.7开始提供;在早期版本中,请使用

def timedelta_total_seconds(td):
    return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / float(10**6)

真的非常感谢!老实说,我忘记了timedelta构造函数。还有,感谢您考虑到“向后兼容性”。 - Крайст

3

您可以使用 total_seconds() 方法:

datetime.timedelta(seconds=datetime.timedelta(minutes=42).total_seconds() * 0.8)
# => datetime.timedelta(0, 2016)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接