将timedelta64类型tripStart_time列转为午夜以来秒数遇报错求助
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_time | seconds |
|---|---|
| 22:30:00 | 81000 |
| 11:00:00 | 39600 |
| 09:00:00 | 32400 |
| 13:30:00 | 48600 |
| 09:00:00 | 32400 |
That's exactly what you're looking for!
内容的提问来源于stack exchange,提问作者ojp

