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

如何用Python/gspread在Google Sheets中仅对比dd/mm与dd/mm/yyyy日期?

解决Google Sheets日期匹配问题(保留原格式并获取单元格位置)

Python + gspread完全支持这类日期对比,无需修改原有日期格式,以下是可行实现方案:

核心思路

gspread读取Google Sheets中的真实日期时,会自动将其转换为Python的datetime对象。直接提取该对象的日、月属性,与今日的日、月做对比即可,比字符串截取或正则匹配更精准。

具体代码实现

场景1:表格中是真实日期格式(gspread自动转为datetime对象)

from datetime import datetime
import gspread
from oauth2client.service_account import ServiceAccountCredentials

# 初始化gspread连接(根据你的授权方式调整,这里用服务账号示例)
scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name("你的服务账号密钥文件.json", scope)
client = gspread.authorize(creds)
sheet = client.open("目标表格名称").sheet1

# 获取今日的日、月
today = datetime.today()
today_day = today.day
today_month = today.month

# 遍历目标列(示例为A列,从第1行开始)
target_col = sheet.col_values(1)
matched_cells = []

for row_idx, cell_val in enumerate(target_col, start=1):
    if isinstance(cell_val, datetime):
        # 提取单元格日期的日、月
        cell_day = cell_val.day
        cell_month = cell_val.month
        # 对比匹配
        if cell_day == today_day and cell_month == today_month:
            matched_cells.append(f"A{row_idx}")

print("匹配的单元格位置:", matched_cells)

场景2:表格中是文本格式的dd/mm/yyyy日期

如果表格里的日期是手动输入的文本而非真实日期格式,可先将文本转为datetime对象再对比:

from datetime import datetime
import gspread
from oauth2client.service_account import ServiceAccountCredentials

# 初始化连接部分同场景1,此处省略
# ...

today_str = datetime.today().strftime('%d/%m')
target_col = sheet.col_values(1)
matched_cells = []

for row_idx, cell_val in enumerate(target_col, start=1):
    try:
        # 将文本日期转为datetime对象,提取dd/mm格式字符串
        cell_date = datetime.strptime(cell_val, '%d/%m/%Y')
        cell_date_str = cell_date.strftime('%d/%m')
        if cell_date_str == today_str:
            matched_cells.append(f"A{row_idx}")
    except ValueError:
        # 跳过非法日期格式的单元格
        continue

print("匹配的单元格位置:", matched_cells)

注意事项

  • 优先用datetime对象对比,避免字符串格式不一致问题(比如05/03和5/3的字符串匹配误差)
  • gspread读取真实日期时自动转datetime是默认行为,无需额外配置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 14:15:13