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

如何用Python在Excel表格中打印与今日日期相同的日期?

问题分析与解决代码

你的代码无输出主要有两个核心问题:

1. iter_cols的遍历逻辑错误

iter_cols 遍历单列时,每次循环拿到的是整列所有行的值组成的元组,而非单个单元格的值。直接用这个元组和 date.today()(一个date对象)比较,永远不会相等,自然没有输出。

2. Excel日期的类型匹配问题

Excel中的日期通过openpyxl读取后,可能是 datetime.datetime(带时间部分)或 datetime.date 对象。如果是前者,直接和 date.today() 比较会不匹配,需要先转换为date类型。

修正后的代码方案

方案一:用iter_rows遍历行(更直观)

from datetime import date, datetime
# 假设你已经通过openpyxl加载了workbook和sheet
present = date.today()

# 遍历第3列,从第2行到最后一行
for row in sheet.iter_rows(
    min_col=3,
    max_col=3,
    min_row=2,
    max_row=sheet.max_row,
    values_only=True
):
    cell_value = row[0]  # 取当前行第3列的单元格值
    # 处理不同类型的日期值
    if isinstance(cell_value, datetime):
        cell_date = cell_value.date()
    elif isinstance(cell_value, date):
        cell_date = cell_value
    else:
        continue  # 跳过非日期类型的单元格
    
    if cell_date == present:
        print(cell_date)

方案二:修正iter_cols的遍历逻辑

from datetime import date, datetime
present = date.today()

# 遍历第3列,先拿到整列的所有值,再逐个遍历单元格
for col in sheet.iter_cols(
    min_col=3,
    max_col=3,
    min_row=2,
    max_row=sheet.max_row,
    values_only=True
):
    for cell_value in col:
        if isinstance(cell_value, datetime):
            cell_date = cell_value.date()
        elif isinstance(cell_value, date):
            cell_date = cell_value
        else:
            continue
        
        if cell_date == present:
            print(cell_date)

额外注意事项

如果你的Excel单元格是文本格式的日期字符串(比如"2024-05-20"),需要先将字符串转换为date对象再比较,示例代码:

# 假设日期字符串格式是YYYY-MM-DD
try:
    cell_date = datetime.strptime(cell_value, "%Y-%m-%d").date()
except ValueError:
    continue  # 格式不匹配则跳过

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 11:55:13