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

如何在Pandas/Jupyter Notebook中将时间列表转为秒并计算时间差

解决时间戳字符串差值计算的类型错误

你遇到的unsupported operand type(s) for -: 'str' and 'str'错误,核心原因是字符串不能直接做减法运算。你的romulus列表里存的是字符串格式的时间,必须先把它们转换成Python的datetime对象,才能进行时间差计算。

另外原代码还有两个逻辑问题:

  • 循环从0开始的话,第一次循环i-1会是-1,取到列表最后一个元素,完全不符合“相邻时间对比”的需求,应该从索引1开始遍历
  • diff.total_seconds是方法引用,必须加括号()才能调用获取实际秒数

修正后的代码

from datetime import datetime

# 各机器已完成包的时间戳字符串列表
romulus = ['2021/12/01 08:03:53', '2021/12/01 08:07:28', '2021/12/01 08:11:57', '2021/12/01 08:14:01', '2021/12/01 08:16:43']

def get_rom(romulus):
    rom_list = []
    # 先把所有时间字符串转成可计算的datetime对象
    time_objs = [datetime.strptime(t, '%Y/%m/%d %H:%M:%S') for t in romulus]
    # 从第2个元素开始,和前一个元素计算时间差
    for i in range(1, len(time_objs)):
        # 后一个时间减前一个,得到正的时间间隔
        diff = time_objs[i] - time_objs[i-1]
        diff_in_seconds = diff.total_seconds()
        rom_list.append(diff_in_seconds)
    return rom_list

print(get_rom(romulus))

关键说明

  • datetime.strptime(t, '%Y/%m/%d %H:%M:%S'):按照时间字符串的格式,把字符串解析成datetime对象,格式符必须和你的时间字符串完全匹配
  • 循环范围range(1, len(time_objs)):确保每次拿当前元素和前一个元素对比,精准计算相邻时间的差值
  • diff.total_seconds():调用方法获取时间差的总秒数,返回浮点数,如果需要整数结果可以用int(diff.total_seconds())转换

运行后会输出:[215.0, 269.0, 124.0, 162.0],对应每两组相邻时间的间隔秒数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 04:55:20