如何在 timedelta 中将秒数转换为以 HH:MM:SS 表示的时间
How to Convert Seconds to Time Expressed in HH:MM:SS in timedelta
我有一个数据框,我想在其中将持续时间(以秒为单位)添加到开始时间列以获得结束时间。开始时间和结束时间列为 datetime64[ns] 类型,而持续时间为 [int64] 类型
start-time,duration
2012-01-02 05:57:38,1168
2012-04-02 06:18:39,58
我首先将持续时间列转换为 timedelta 格式的 hh:mm:ss,以便我进行加法运算。 duration 列已成功转换为 timedelta,但显示为 1970-01-01T00:19:28Z。我怎样才能摆脱 1970 年的日期部分,只保留 hh:mm:ss 时间部分,但仍然是 timedelta 类型。
我试过以下
df['duration'] = df['duration'].astype('float64')
df['duration'] = pd.to_datetime(df['duration'], unit='s').dt.strftime("%H:%M:%S")
df['duration'] = pd.to_timedelta(df['duration'])
df['end-time'] = df['start-time'] + df['duration']
输出
start-time,end-time,duration
2012-04-02 05:57:38,2012-04-02 06:17:06,1970-01-01T00:19:28Z
2012-04-02 06:18:39,2012-04-02 06:19:37,1970-01-01T00:00:58Z
期望输出
start-time,end-time,duration
2012-01-02 05:57:38,2012-04-02 06:17:06,00:19:28
2012-04-02 06:18:39,2012-04-02 06:19:37,00:00:58
您不需要从 int -> float -> datetime -> timedelta 转换
你可以直接从 int seconds 到 timedelta
df['duration'] = pd.to_timedelta(df['duration'], unit='s')
df['end-time'] = df['start-time'] + df['duration']
df = df[['start-time','end-time','duration']]
输入
start-time duration
2012-01-02 05:57:38 1168
2012-04-02 06:18:39 58
输出
start-time end-time duration
2012-01-02 05:57:38 2012-01-02 06:17:06 0 days 00:19:28
2012-04-02 06:18:39 2012-04-02 06:19:37 0 days 00:00:58
我有一个数据框,我想在其中将持续时间(以秒为单位)添加到开始时间列以获得结束时间。开始时间和结束时间列为 datetime64[ns] 类型,而持续时间为 [int64] 类型
start-time,duration
2012-01-02 05:57:38,1168
2012-04-02 06:18:39,58
我首先将持续时间列转换为 timedelta 格式的 hh:mm:ss,以便我进行加法运算。 duration 列已成功转换为 timedelta,但显示为 1970-01-01T00:19:28Z。我怎样才能摆脱 1970 年的日期部分,只保留 hh:mm:ss 时间部分,但仍然是 timedelta 类型。
我试过以下
df['duration'] = df['duration'].astype('float64')
df['duration'] = pd.to_datetime(df['duration'], unit='s').dt.strftime("%H:%M:%S")
df['duration'] = pd.to_timedelta(df['duration'])
df['end-time'] = df['start-time'] + df['duration']
输出
start-time,end-time,duration
2012-04-02 05:57:38,2012-04-02 06:17:06,1970-01-01T00:19:28Z
2012-04-02 06:18:39,2012-04-02 06:19:37,1970-01-01T00:00:58Z
期望输出
start-time,end-time,duration
2012-01-02 05:57:38,2012-04-02 06:17:06,00:19:28
2012-04-02 06:18:39,2012-04-02 06:19:37,00:00:58
您不需要从 int -> float -> datetime -> timedelta 转换
你可以直接从 int seconds 到 timedelta
df['duration'] = pd.to_timedelta(df['duration'], unit='s')
df['end-time'] = df['start-time'] + df['duration']
df = df[['start-time','end-time','duration']]
输入
start-time duration
2012-01-02 05:57:38 1168
2012-04-02 06:18:39 58
输出
start-time end-time duration
2012-01-02 05:57:38 2012-01-02 06:17:06 0 days 00:19:28
2012-04-02 06:18:39 2012-04-02 06:19:37 0 days 00:00:58