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

使用Python(gspread和pandas)更新Google Sheets时如何保留日期格式

解决gspread更新Google Sheets后日期转为文本导致QUERY函数失效的问题

问题根源:

  • 用get_all_values()读取数据时,Google Sheets的日期会被转为纯字符串存入pandas
  • 默认的ws.update()使用RAW模式写入数据,会给字符串添加单引号强制文本格式,导致Google Sheets无法自动识别为日期类型,最终让QUERY函数无法匹配日期

解决方案

修改代码核心两点:

  1. 读取数据时解析日期列,确保格式统一
  2. 更新表格时使用USER_ENTERED模式,让Google Sheets自动识别数据类型

修改后的完整代码

import gspread
import pandas as pd
from google.auth import default
from google.auth.transport.requests import Request

# 抽离认证逻辑,避免重复执行
def get_authorized_client():
    auth.authenticate_user()
    creds, _ = default()
    # 刷新过期凭证(如果需要)
    if creds.expired and creds.refresh_token:
        creds.refresh(Request())
    return gspread.authorize(creds)

def load(date_columns=['你的日期列名']):
    gc = get_authorized_client()
    wb = gc.open_by_key('你的表格key')
    ws = wb.worksheet("worksheet")
    rows = ws.get_all_values()

    df = pd.DataFrame.from_records(rows[1:], columns=rows[0])
    # 解析日期列,按日/月/年格式转为datetime类型
    for col in date_columns:
        df[col] = pd.to_datetime(df[col], dayfirst=True)
    return df

def update(cols):
    base = load()
    base.drop(columns=cols, axis=1, inplace=True)

    # 将datetime类型转回日/月/年格式的字符串
    date_cols = base.select_dtypes(include=['datetime64[ns]']).columns
    for col in date_cols:
        base[col] = base[col].dt.strftime('%d/%m/%Y')

    new_bs = [base.columns.tolist()] + base.values.tolist()

    gc = get_authorized_client()
    wb = gc.open_by_key('你的表格key')
    ws = wb.worksheet("worksheet")

    ws.clear()
    # 关键参数:USER_ENTERED 让Google Sheets自动识别数据类型
    ws.update('A1', new_bs, value_input_option='USER_ENTERED')

columns_to_remove = ['column1', 'column2', "column3", "column4", "column5"]
update(columns_to_remove)

关键说明

  • value_input_option='USER_ENTERED':这是解决问题的核心,告诉gspread以用户手动输入的方式写入数据,Google Sheets会自动识别日期、数字等格式,不会添加单引号强制文本。
  • 日期解析与格式化:读取时将字符串转为datetime,确保格式统一;更新前转回日/月/年的字符串,保证Google Sheets能正确识别为日期类型(如果你的日期格式是月/日/年,把dayfirst=True改成dayfirst=False即可)。
  • 优化认证逻辑:把认证代码抽成独立函数,避免每次load和update都重复执行认证,提升效率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 18:40:56