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

求助:Python实现两文件时间相减并写入新文件的方法

...
time
8.07
12.05
time

我尝试过Python的`datetime`模块,但不知道具体怎么实现分块对应和差值计算,请求帮助。

---

# 解决方案

可以通过以下步骤实现,核心是用`datetime`解析时间字符串,计算时间差后转换为秒数并格式化:

### 1. 读取并处理文件B的基准时间
先从文件B中提取所有基准时间,去掉每行开头的`# `,并转换为可计算的时间对象:
```python
from datetime import datetime

def load_base_times(b_file_path):
    base_times = []
    with open(b_file_path, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if line.startswith('# '):
                time_str = line[2:]
                # 解析时间字符串为datetime对象(日期用固定值,不影响时间差)
                base_dt = datetime.strptime(time_str, '%H:%M:%S.%f')
                base_times.append(base_dt)
    return base_times

2. 读取文件A的分块时间并计算差值

遍历文件A的内容,按time分割成块,每个块对应一个基准时间,计算每个时间与基准时间的差值(转换为秒,保留两位小数):

def process_time_blocks(a_file_path, base_times):
    result = []
    current_block = []
    block_index = 0

    with open(a_file_path, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            if line == 'time':
                # 处理当前已收集的时间块
                if current_block and block_index < len(base_times):
                    base_dt = base_times[block_index]
                    for time_str in current_block:
                        current_dt = datetime.strptime(time_str, '%H:%M:%S.%f')
                        # 计算时间差并转换为秒
                        diff_seconds = (current_dt - base_dt).total_seconds()
                        # 保留两位小数加入结果
                        result.append(f"{diff_seconds:.2f}")
                # 添加分隔符到结果
                result.append('time')
                # 重置当前块,切换到下一个基准时间
                current_block = []
                block_index += 1
            else:
                current_block.append(line)
    
    return result

3. 输出结果

把处理后的结果打印或写入文件:

def main():
    base_times = load_base_times('fileB.txt')
    processed_result = process_time_blocks('fileA.txt', base_times)
    
    # 打印结果
    for line in processed_result:
        print(line)
    
    # 写入文件(可选)
    with open('output.txt', 'w', encoding='utf-8') as f:
        f.write('\n'.join(processed_result))

if __name__ == '__main__':
    main()

关键说明

  • 时间解析:用strptime按%H:%M:%S.%f格式解析,支持到微秒级的时间字符串
  • 时间差计算:直接用datetime对象相减,通过total_seconds()获取精确的秒数差值
  • 分块对应:遍历文件A时,遇到time就切换到下一个基准时间,确保块与基准一一匹配
  • 格式控制:用:.2f格式化差值,保证输出两位小数的精度

内容的提问来源于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 04:37:10