将 timedelta
对象转换为秒数在 Python 中可通过以下方法实现,具体操作如下:
一、使用 total_seconds()
方法
这是最直接的方法,timedelta
对象自带 total_seconds()
方法,可直接返回总秒数(包含小数部分)。
示例代码:
from datetime import timedelta
# 创建 timedelta 对象
td = timedelta(days=2, hours=3, minutes=30, seconds=15, milliseconds=500)
# 转换为秒数
total_seconds = td.total_seconds()
print(total_seconds) # 输出: 86400*2 + 3*3600 + 30 + 15.5 = 172545.5
二、手动计算秒数
若需分别获取小时、分钟、秒等部分,可结合 divmod
函数进行拆分。
示例代码:
# 创建 timedelta 对象
td = timedelta(days=2, hours=3, minutes=30, seconds=15, milliseconds=500)
# 转换为总秒数
total_seconds = int(td.total_seconds())
# 分解为小时、分钟、秒
hours, remainder = divmod(total_seconds, 3600)
minutes, seconds = divmod(remainder, 60)
milliseconds = td.microseconds // 1000
# 格式化输出
formatted_time = f"{hours:02}:{minutes:02}:{seconds:02}.{milliseconds:03}"
print(formatted_time) # 输出: 51:30:15.500
三、在 Pandas 中批量转换
若处理 DataFrame 中的 timedelta
列,可使用 dt.components
属性提取各部分并格式化。
示例代码:
import pandas as pd
# 创建示例 DataFrame
data = {'time': ['2 days 03:29:05', '1 day 01:57:53']}
df = pd.DataFrame(data)
df['time'] = pd.to_timedelta(df['time'])
# 新增 'new' 列,格式化为 h:mm:ss
df[ ] = df['time'].dt.components.apply(
lambda x: f"{x.days*24+x.hours:02}:{x.minutes:02}:{x.seconds:02}"
)
print(df)
# 输出:
# id time new
# 0 1123 2 days 03:29:05 51:29:05
# 1 2342 1 day 01:57:53 25:57:53
四、注意事项
-
total_seconds()
返回浮点数,若需整数秒数,可使用int()
函数截取。 -
处理毫秒时,可通过
microseconds
属性获取并转换。
以上方法适用于 Python 3.3 及以上版本,Pandas 版本需≥ 0.24.2 以支持 dt.components
属性。