You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现两文件多事件时间差计算并写入新文件

时间数据减法运算实现方案

问题说明

数据格式

基准时间数据

每行以#开头,对应单个事件组的基准时间:

# 04:13:53.7
# 06:04:37.0
# 07:36:30.7

分组事件数据

以sta phase time wt作为分组分隔标识,每组对应一个基准时间:

sta phase time wt
GENI P 04:14:14.4 1.0
GENI S 04:14:29.9 1.0
SMPI P 04:14:22.6 1.0
SMPI S 04:14:44.7 1.0
ATNI P 04:17:30.1 1.0
SOEI P 04:17:39.4 1.0
sta phase time wt
GENI P 06:04:45.7 1.0
GENI S 06:04:49.5 1.0
JAY P 06:04:51.9 1.0
JAY S 06:05:01.6 1.0
ERPI P 06:05:33.4 1.0
FAKI P 06:06:26.9 0.0
SWI P 06:06:42.0 0.0
BSMI P 06:06:50.4 0.0
SAUI P 06:06:58.4 0.0
KRAI P 06:07:19.9 0.0
sta phase time wt
GENI P 07:36:52.4 1.0
GENI S 07:37:10.7 1.0
JAY P 07:36:58.3 1.0
JAY S 07:37:16.9 1.0
sta phase time wt

核心需求

将分组事件数据中time列的时间与对应基准时间相减,得到以秒为单位的时间差(支持四舍五入),输出保留原分组结构,替换time列为计算后的差值。


Python实现方案

以下代码可直接处理两类数据,完成时间差计算与格式输出:

from datetime import datetime

def parse_time_to_sec(time_str):
    """将HH:MM:SS.f格式的时间字符串转换为总秒数"""
    dt = datetime.strptime(time_str, '%H:%M:%S.%f')
    return dt.hour * 3600 + dt.minute * 60 + dt.second + dt.microsecond / 1000000

# 读取并解析基准时间
base_times = []
with open('base_times.txt', 'r', encoding='utf-8') as f:
    for line in f:
        stripped_line = line.strip()
        if stripped_line.startswith('#'):
            time_str = stripped_line[2:]  # 去掉#和空格
            base_times.append(parse_time_to_sec(time_str))

# 处理事件数据并生成输出
current_base_idx = 0
with open('event_data.txt', 'r', encoding='utf-8') as f_in, \
     open('output.txt', 'w', encoding='utf-8') as f_out:
    
    for line in f_in:
        line = line.strip()
        if not line:
            f_out.write('\n')
            continue
        
        # 遇到分组标识,切换基准时间并原样写入
        if line == 'sta phase time wt':
            f_out.write(f"{line}\n")
            if current_base_idx < len(base_times) - 1:
                current_base_idx += 1
            continue
        
        # 处理事件行,计算时间差
        parts = line.split()
        if len(parts) != 4:
            f_out.write(f"{line}\n")
            continue
        
        sta, phase, event_time_str, wt = parts
        event_sec = parse_time_to_sec(event_time_str)
        base_sec = base_times[current_base_idx]
        time_diff = event_sec - base_sec
        
        # 四舍五入,自动处理整数/小数格式
        rounded_diff = round(time_diff, 1)
        if rounded_diff.is_integer():
            rounded_diff = int(rounded_diff)
        
        # 写入结果行
        f_out.write(f"{sta} {phase} {rounded_diff} {wt}\n")

代码说明

  1. 时间解析:通过datetime.strptime将时间字符串转换为总秒数,避免时分秒的复杂计算
  2. 基准时间匹配:遇到分组标识sta phase time wt时,自动切换到下一个基准时间,保证每组对应正确的基准
  3. 格式处理:计算后的时间差自动四舍五入,若为整数则去掉小数部分,符合需求示例格式
  4. 兼容性:保留原文件中的空行和异常行,避免数据丢失

内容的提问来源于stack exchange,提问作者rainzx27

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 02:45:01