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

将timedelta64类型tripStart_time列转为午夜以来秒数遇报错求助

How to Calculate Seconds Since Midnight from a Timedelta Column in Pandas

Hey there! The error you're seeing makes total sense—let's break this down and fix it.

Why the Error Happens

Your tripStart_time column is a timedelta64[ns] Series, and you can't directly access .hour on the Series itself. That attribute exists for individual timedelta objects, but for a Series, you need to use Pandas' .dt accessor to get element-level time components.

Solution 1: Use dt.total_seconds() (Simplest Method)

Since your tripStart_time already represents the time elapsed since midnight (as a timedelta), you can directly get the total seconds using the built-in total_seconds() method via the .dt accessor:

df_time['seconds'] = df_time['tripStart_time'].dt.total_seconds()

This will give you the full number of seconds including any fractional parts (like milliseconds if they existed), and it's the cleanest approach. For your first row (22:30:00), this returns 81000.0 which is exactly 22*3600 + 30*60.

Solution 2: Calculate Using Hour/Minute/Second Components

If you want to replicate your original approach (only using integer hour/minute/second values), just add the .dt accessor before each time component:

df_time['seconds'] = (df_time['tripStart_time'].dt.hour * 3600) + \
                     (df_time['tripStart_time'].dt.minute * 60) + \
                     df_time['tripStart_time'].dt.second

This will give you an integer result (e.g., 81000 for the first row) instead of a float, which might be what you prefer if you don't need fractional seconds.

Let's Test It with Your Data

For your sample DataFrame, both methods will produce:

tripStart_timeseconds
22:30:0081000
11:00:0039600
09:00:0032400
13:30:0048600
09:00:0032400

That's exactly what you're looking for!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 18:12:41