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

如何将DataFrame中的24小时制时间列转换为总秒数?

Hey there! Converting a HH:MM:SS time string column to total seconds in pandas is straightforward—here are a couple of clean, efficient ways to do it, using your sample data as a starting point.

First, let's complete your sample DataFrame code (since it was cut off) so we have a runnable example:

import pandas as pd
import random

def randomTime():
    rtime = int(random.random()*86400)
    hours = int(rtime/3600)
    minutes = int((rtime - hours*3600)/60)
    seconds = rtime - hours*3600 - minutes*60
    time_string = '%02d:%02d:%02d' % (hours, minutes, seconds)
    return time_string

time = [randomTime() for _ in range(8)]
events = ['ABC','DEF','GHI','JKL','ABC','DEF','GHI','JKL']  # Completed the Events list

df = pd.DataFrame({'Time': time, 'Events': events})
print(df)

Method 1: Use pd.to_timedelta (Simplest & Most Efficient)

This is the go-to method—it directly converts your time string to a timedelta object, then we can grab the total seconds with total_seconds():

df['Total_Seconds'] = pd.to_timedelta(df['Time']).dt.total_seconds()
print(df)

Method 2: Manual Calculation (If You Want to Break It Down)

If you prefer to see the individual components (hours, minutes, seconds) used in the calculation, here are two ways to do that:

Option A: Split the Time String

Split the HH:MM:SS string into separate columns, convert them to integers, then compute the total seconds:

# Split the Time column into hours, minutes, seconds
df[['Hours', 'Minutes', 'Seconds']] = df['Time'].str.split(':', expand=True).astype(int)

# Calculate total seconds
df['Total_Seconds'] = df['Hours'] * 3600 + df['Minutes'] * 60 + df['Seconds']

# Optional: Remove the intermediate columns if you don't need them
df = df.drop(['Hours', 'Minutes', 'Seconds'], axis=1)
print(df)

Option B: Use Datetime Conversion

Convert the time string to a datetime object (we can ignore the date part since we only care about time), then extract the hour, minute, and second values to compute total seconds:

# Convert Time to datetime format (using a dummy date under the hood)
df['Time_Datetime'] = pd.to_datetime(df['Time'], format='%H:%M:%S')

# Calculate total seconds from datetime components
df['Total_Seconds'] = df['Time_Datetime'].dt.hour * 3600 + df['Time_Datetime'].dt.minute * 60 + df['Time_Datetime'].dt.second

# Optional: Drop the datetime column
df = df.drop('Time_Datetime', axis=1)
print(df)

All these methods will give you the total number of seconds since midnight for each time entry. Method 1 is the most concise and performs best for large datasets.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:55:15