You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何将时间字符串列表与浮点数列表相乘?

解决时间字符串与浮点数相乘的问题

核心思路

时间字符串无法直接与数字运算,必须先转换为总秒数(数值类型),完成乘法后再转回时分秒格式。

错误原因分析

  • time_string*float_num:Python列表的*操作仅支持与整数相乘(实现列表重复),不能直接对两个列表做元素级乘法。
  • time_string[0].dt.datetime.strptime(...):dt是Pandas Series专属属性,普通字符串对象没有该方法,需先将字符串转为Pandas时间序列。
  • float(test):datetime.datetime是时间点对象,无法直接转为浮点数,应提取时长对应的总秒数再做数值运算。

实现方法(纯Python版)

time_string = ['0:00:00', '0:00:00', '0:00:16', '0:00:09', '0:02:39', '0:07:19',
                 '0:02:00', '0:08:33', '0:08:30', '0:14:13', '0:07:24', '0:10:08']
float_num = [0.0, 1.1, 3.1, 10.1, 9.1, 5.1, 4.1, 2.1, 8.1, 6.1, 16.1, 17.1]

result = []
for ts, num in zip(time_string, float_num):
    # 拆分时间字符串为时分秒并转为数值
    h, m, s = map(float, ts.split(':'))
    # 计算总秒数
    total_sec = h * 3600 + m * 60 + s
    # 执行乘法运算
    new_sec = total_sec * num
    # 将新秒数转回时分秒格式
    hours = int(new_sec // 3600)
    rem_sec = new_sec % 3600
    minutes = int(rem_sec // 60)
    seconds = rem_sec % 60
    # 格式化输出(分钟补零,秒数保留两位小数)
    result.append(f"{hours}:{minutes:02d}:{seconds:.2f}")

print(result)

实现方法(Pandas版,更简洁)

import pandas as pd

time_series = pd.to_timedelta(time_string)
float_series = pd.Series(float_num)

# 计算总秒数相乘后转回时长格式
new_total_sec = time_series.dt.total_seconds() * float_series
new_timedelta = pd.to_timedelta(new_total_sec, unit='s')

# 格式化时分秒字符串,补全秒数小数位
result = new_timedelta.astype(str).str.split().str[-1].apply(
    lambda x: x if '.' in x else f"{x}.00"
).tolist()

print(result)

输出结果示例

['0:00:00.00', '0:00:00.00', '0:00:49.60', '0:01:30.90', '0:23:12.90', '0:36:36.90', '0:08:12.00', '0:17:45.30', '0:52:51.00', '0:56:12.90', '2:00:26.40', '2:52:16.80']

内容的提问来源于stack exchange,提问作者Mark Yo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 17:33:12