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

使用Python为Excel单元格填充递增时间的技术求助

Python填充Excel时间列:空单元格按前一个有效时间递增1小时

问题描述

我不是专业程序员,只会写点简单代码。现在需要用Python处理一份Excel文件,文件有5列,其中B列是hh:mm:ss格式的时间字段,但不是所有单元格都有值。需求是:当某单元格有时间值时,后续空单元格依次递增1小时,直到遇到下一个已有时间值,再重复这个逻辑。

示例:

  • B20: 13:00:00
  • B26: 17:00:00
  • B28: 19:00:00
  • B30-B32: 10:00, 11:00, 12:00

我写了下面的代码但没法正常运行,求帮忙:

# Iterate over all rows in the worksheet
for row in worksheet.iter_rows(min_row=2):
    # Get the value of the cell in column B for the current row
    cell_value = row[1].value

    # Check if the cell is not empty
    if cell_value is not None:
        # Convert the value of the cell to a string
        if isinstance(cell_value, datetime.time):
            cell_value = str(cell_value)
        cell_value = datetime.datetime.strptime(cell_value, '%H:%M:%S').time()

        # Get the index of the current row
        row_index = row[0].row

        # Iterate over the rows below the current row
        for i in range(row_index, worksheet.max_row + 1):
            # Get the value of the cell in column B for the current row
            next_cell_value = worksheet.cell(row=i, column=2).value

            # Check if the cell is empty
            if next_cell_value == '' or next_cell_value is None:
                # Set the value of the cell to the updated datetime object
                worksheet.cell(row=i, column=2).value = cell_value.strftime('%H:%M:%S')
            else:
                # Convert the value of the cell to a string
                if isinstance(next_cell_value, datetime.time):
                    next_cell_value = str(next_cell_value)
                next_cell_value = datetime.datetime.strptime(next_cell_value, '%H:%M:%S').time()

                # Add 1 hour to the datetime object
                next_cell_value = (datetime.datetime.combine(datetime.date.today(), next_cell_value) + datetime.timedelta(hours=1)).time()

                # Set the value of the cell to the updated datetime object
                worksheet.cell(row=i, column=2).value = next_cell_value.strftime('%H:%M:%S')

问题分析

你的代码存在几个关键问题:

  1. 重复处理行:外层循环遍历所有行,每次遇到非空单元格就重新处理下方所有行,导致已填充的单元格被反复覆盖
  2. 逻辑错误:内层循环遇到已有值的单元格时,直接给它加1小时覆盖原数据,这不符合需求(原数据应该保留,作为新的起始时间)
  3. 未维护递增时间:空单元格都用最初的cell_value填充,没有实现每次递增1小时的逻辑

修正后的代码

import datetime
from openpyxl import load_workbook

# 替换为你的Excel文件路径
wb = load_workbook('your_excel_file.xlsx')
ws = wb.active

# 记录当前要使用的时间,初始为None
current_time = None

# 遍历B列所有行(从第2行开始,假设第1行是表头)
for row_num in range(2, ws.max_row + 1):
    cell = ws.cell(row=row_num, column=2)
    cell_val = cell.value

    if cell_val is not None and cell_val != '':
        # 处理已有时间值,更新current_time
        if isinstance(cell_val, datetime.time):
            current_time = cell_val
        else:
            # 将字符串格式的时间转为time对象
            current_time = datetime.datetime.strptime(str(cell_val), '%H:%M:%S').time()
    else:
        # 空单元格,基于current_time递增1小时
        if current_time is not None:
            # 把time对象转为datetime才能进行时间运算
            dt = datetime.datetime.combine(datetime.date.today(), current_time)
            dt += datetime.timedelta(hours=1)
            current_time = dt.time()
            # 填充格式化后的时间字符串
            cell.value = current_time.strftime('%H:%M:%S')

# 保存修改后的文件,建议用新文件名避免覆盖原文件
wb.save('updated_excel_file.xlsx')

代码说明

  • 单次遍历:只遍历B列一次,避免重复处理导致的覆盖问题
  • 维护当前时间:用current_time变量跟踪当前要填充的时间,遇到新的有效时间时更新它
  • 时间运算:由于datetime.time对象不支持直接加减,先转为datetime.datetime对象完成递增,再转回time对象
  • 保留原数据:遇到已有值的单元格时仅更新current_time,不会修改原数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 02:20:33