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

Python读取Excel日期与本地日期匹配失败,如何去除日期中的时间部分?

问题原因分析
  • 不匹配的核心原因是datetime.datetime类型的对比会精确到微秒级别:你从Excel读取的日期转换后时分秒均为0,而datetime.datetime.now()返回的是当前实时时间,包含时分秒和微秒,哪怕日期相同,时间部分不一致也会判定为不相等
  • Excel日期底层确实以浮点型存储,整数部分代表距起始日期的天数,小数部分代表当天的时间占比,修改单元格显示格式不会改变底层存储的浮点值,所以读取后默认会携带时间部分
修复方案

你只需要将两个时间都转换为仅包含日期的date类型再对比即可,无需多余的字符串转码操作,修正后的代码如下:

import datetime
import xlrd
from xlrd import open_workbook

book = open_workbook('D:/ma.xls')
sheet = book.sheet_by_index(0)
# 读取Excel存储的浮点型日期值
excel_float_date = sheet.cell_value(0,1)
# 转换为datetime对象
excel_datetime = datetime.datetime(*xlrd.xldate_as_tuple(excel_float_date, book.datemode))
# 仅提取日期部分(去掉时分秒)
excel_date = excel_datetime.date()
# 获取当前本地日期(不含时间部分)
current_date = datetime.datetime.now().date()

print(excel_datetime)
print(datetime.datetime.now())
if current_date == excel_date:
    print("match")
else:
    print("Date not match")
可选补充说明

如果你需要保留datetime类型同时清空时间部分,可以使用replace方法统一把两个时间的时分秒微秒都设为0再对比,写法如下:

excel_clear_time = excel_datetime.replace(hour=0, minute=0, second=0, microsecond=0)
current_clear_time = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
if current_clear_time == excel_clear_time:
    print("match")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:54:01