python中带浮点的Timedelta乘法

2024-10-05 14:23:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个日期,可以像往常一样计算时间增量。

但我想用得到的时间增量来计算一些百分比:

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)-精度会受到影响。


Tags: 间隔time时间float增量fullint百分比
2条回答

您可以转换为总秒数并再次转换:

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

^{}可从Python2.7获得;在早期版本中使用

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

您可以使用^{}

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

相关问题 更多 >