下面我将为您详细讲解“pandas 两列时间相减换算为秒的方法”的完整攻略。
首先我们需要使用pandas中的to_datetime
方法将时间字符串转换为datetime类型。具体示例代码如下:
import pandas as pd
df = pd.DataFrame({
'start_time': ['2022-01-01 00:00:00', '2022-01-01 00:01:00', '2022-01-01 00:02:00'],
'end_time': ['2022-01-01 00:01:00', '2022-01-01 00:03:00', '2022-01-01 00:04:00']
})
df['start_time'] = pd.to_datetime(df['start_time'])
df['end_time'] = pd.to_datetime(df['end_time'])
上面的代码将start_time
和end_time
列分别转换为datetime类型。
接下来,我们可以使用Timedelta
方法来计算两个时间之差,将结果转换为秒。具体示例代码如下:
df['time_delta_sec'] = (df['end_time'] - df['start_time']).dt.total_seconds()
上面的代码将计算end_time
减去start_time
的时间差,并将结果转换为秒,并将结果保存在time_delta_sec
列中。
完整的处理代码如下:
import pandas as pd
df = pd.DataFrame({
'start_time': ['2022-01-01 00:00:00', '2022-01-01 00:01:00', '2022-01-01 00:02:00'],
'end_time': ['2022-01-01 00:01:00', '2022-01-01 00:03:00', '2022-01-01 00:04:00']
})
df['start_time'] = pd.to_datetime(df['start_time'])
df['end_time'] = pd.to_datetime(df['end_time'])
df['time_delta_sec'] = (df['end_time'] - df['start_time']).dt.total_seconds()
print(df)
输出结果:
start_time end_time time_delta_sec
0 2022-01-01 00:00:00 2022-01-01 00:01:00 60.0
1 2022-01-01 00:01:00 2022-01-01 00:03:00 120.0
2 2022-01-01 00:02:00 2022-01-01 00:04:00 120.0
以上就是使用pandas计算两个时间之差并转换为秒的方法。最后再给出一个示例代码:
import pandas as pd
df = pd.DataFrame({
'start_time': ['2022-01-01 00:00:00', '2022-01-01 00:05:00', '2022-01-01 00:10:00'],
'end_time': ['2022-01-01 00:01:00', '2022-01-01 00:08:00', '2022-01-01 00:15:00']
})
df['start_time'] = pd.to_datetime(df['start_time'])
df['end_time'] = pd.to_datetime(df['end_time'])
df['time_delta_sec'] = (df['end_time'] - df['start_time']).dt.total_seconds()
print(df)
输出结果:
start_time end_time time_delta_sec
0 2022-01-01 00:00:00 2022-01-01 00:01:00 60.0
1 2022-01-01 00:05:00 2022-01-01 00:08:00 180.0
2 2022-01-01 00:10:00 2022-01-01 00:15:00 300.0
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:pandas 两列时间相减换算为秒的方法 - Python技术站