欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

excel 每一行的 年月日时分秒 减去 上一行的年月日时分秒 放到 B 列 用 python 来实现 通义 有大用

下面两个图,  左边是原图, 右边是结果图


image.png       image.png




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.")


普通分类: