将 timedelta 转换为秒

convert timedelta to seconds

我在我的数据框中计算了持续时间,但我想获得以秒为单位的持续时间而不是它给出的持续时间(0 天,00:10:25 等等):

df['duration'] = df['end_date'] - df['start_date']
df.head(2)
    started_at  ended_at    start_date  end_date    duration
0   2021-01-23 16:14:19 2021-01-23 16:24:44 2021-01-23 16:14:19 2021-01-23 16:24:44 0 days 00:10:25
1   2021-01-27 18:43:08 2021-01-27 18:47:12 2021-01-27 18:43:08 2021-01-27 18:47:12 0 days 00:04:04

我尝试了 here 中的一些解决方案,但我不确定如何正确执行,没有任何效果;例如我试过这个:

df['duration'] = datetime.timedelta.total_seconds(df['duration'])

但是它说

TypeError: descriptor 'total_seconds' for 'datetime.timedelta' objects doesn't apply to a 'Series' object

您应该可以使用 total_seconds 方法。但是,您需要通过日期时间访问器 dt.

访问该方法
>>> df['duration'].dt.total_seconds()

但是,如果系列 Duration 是 strings/object- 你应该使用 pd.to_timedelta

>>> pd.to_timedelta(df['duration']).dt.total_seconds()

我会尝试运行申请你的系列

df['duration'] = df['duration'].apply(datetime.timedelta.total_seconds)

来自你的错误。它表明您正在尝试 运行 它在一个系列