如何 return 给定 pandas 中只有小时-分钟-秒格式的列的总时间(以秒为单位)?

How to return total time in seconds given a column with only hour-minute-second format in pandas?

我有一个 pandas DataFrame,其列的格式为 00:00:00(时、分、秒)。

   'Time'
0  00:01:00
1  00:00:30
2  00:01:30
3  00:00:10

我需要创建一个包含总秒数的列。即

   'Time'    'Time in secs'
0  00:01:00       60
1  00:00:30       30
2  00:01:30       90
3  00:00:10       10

我怎样才能做到这一点?

顺便说一下,当我这样做时:

df['Time'] = pd.to_datetime(df['Time], format = "%H:%M:%S")

时间列显示为 1900-01-01 00:00:00 格式。 :(

如何去掉年月日?

您没有日期,因此最容易使用 Timedelta,并且您的格式完全符合要求。这些正是您想要的属性:total_seconds

pd.to_timedelta(df.Time).dt.total_seconds()
#0    60.0
#1    30.0
#2    90.0
#3    10.0
#Name: Time, dtype: float64

将时间列转换为时间增量并将其除以秒

df['Time in secs'] = pd.to_timedelta(df['Time'])/pd.to_timedelta(1, unit='S')

结果

df['Time in secs']
0    60.0
1    30.0
2    90.0
3    10.0
Name: Time, dtype: float64