import pandas as pd
# 读取 Excel 文件
file_path = 'before.xlsx' # 替换为你的文件路径
df = pd.read_excel(file_path)
# 打印前几行以确认列名
print("DataFrame columns:", df.columns.tolist())
print(df.head())
# 根据实际列名进行修改
timestamp_column_name = 'TRANSDATETIME' # 替换为实际的列名
if timestamp_column_name in df.columns:
# 将时间数据转换为 datetime 类型
df[timestamp_column_name] = pd.to_datetime(df[timestamp_column_name], format='%Y%m%d%H%M%S', errors='coerce')
# 计算相邻两行的时间差,并将结果存入 'B' 列
df['B'] = df[timestamp_column_name].diff()
# 如果你想把时间差显示为总秒数,可以使用以下代码:
df['B'] = df['B'].dt.total_seconds()
# 写回 Excel 文件
output_file_path = 'output_file.xlsx' # 替换为你想要保存的文件路径
df.to_excel(output_file_path, index=False)
print(f"Time differences have been calculated and saved to {output_file_path}")
else:
print(f"Column '{timestamp_column_name}' not found in the DataFrame.")