如何将DataFrame中含天数的timedelta转换为总秒数?
将DataFrame中时间间隔列转为总秒数的解决办法
我尝试把名为ny的DataFrame里的Time Elapsed列转换成总秒数,试了三种方法全失败:
- 执行
ny["Time Elapsed"].time(),报错:AttributeError: 'Series' object has no attribute 'time' - 执行
ny["Time Elapsed"].total_seconds(),报错:AttributeError: 'Series' object has no attribute 'total_seconds' - 执行
ny["Time Elapsed"](int),报错:TypeError: 'Series' object is not callable
从截图能看到,Time Elapsed列存的是00:05:21这类字符串,不是pandas的timedelta类型,这就是方法失效的核心原因。下面给几种可行的解决方式:
方法1:转成timedelta类型再计算(最推荐)
先用pd.to_timedelta把字符串列转成时间间隔类型,再调用dt.total_seconds()拿到总秒数:
import pandas as pd ny["Total Seconds"] = pd.to_timedelta(ny["Time Elapsed"]).dt.total_seconds()
方法2:拆分字符串手动计算
如果列里的时间格式固定是HH:MM:SS,可以拆分后自己计算:
def convert_to_sec(time_str): hours, mins, secs = map(int, time_str.split(':')) return hours * 3600 + mins * 60 + secs ny["Total Seconds"] = ny["Time Elapsed"].apply(convert_to_sec)
方法3:用datetime模块解析
借助datetime的时间解析功能,把字符串转成时间对象后计算差值:
from datetime import datetime ny["Total Seconds"] = ny["Time Elapsed"].apply( lambda x: (datetime.strptime(x, "%H:%M:%S") - datetime(1900, 1, 1)).total_seconds() )
内容的提问来源于stack exchange,提问作者Ab3ila
相关产品推荐
相关产品推荐

