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

1 投票
1 回答
66 浏览
提问于 2025-04-14 18:04

我现在在使用Google Sheets处理一个数据集,在清理数据的过程中,我用Python和一些库,比如gspread和pandas,来删除不必要的列,然后再把清理好的数据更新到电子表格里。不过,我在运行我的Python脚本后遇到了一个问题:我想用Google Sheets的QUERY函数根据一个日期格式的列提取特定数据到另一个工作表,但似乎失败了。看起来我的脚本不小心改变了日期列的格式,导致QUERY函数无法正确识别这些日期。这就出现了一个错误,提示“查询结果为空”。这个问题在我手动删除列时不会出现,只有在运行我的脚本后才会出现,尽管列的格式设置为“自动”。

下面是我使用的代码片段:

def load():
    auth.authenticate_user()
    creds, _ = default()
    gc = gspread.authorize(creds)

    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])
    return df

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

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

    auth.authenticate_user()
    creds, _ = default()
    gc = gspread.authorize(creds)
    wb = gc.open_by_key('key')
    ws = wb.worksheet("worksheet")

    ws.clear()

    ws.update('A1', new_bs)

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

经过分析,我发现了日期格式的问题。在我运行Python脚本更新Google Sheets工作表后,我注意到日期值前面多了一个撇号,这让它们被格式化成了文本(比如'28/02/2019)。这使得Google Sheets无法将这些条目识别为日期。虽然手动去掉前面的撇号可以把文本转换回日期格式,但这样手动操作效率不高。

1 个回答

1

在你的情况下,下面这个修改怎么样?

原来的代码:

ws.update('A1', new_bs)

修改后的代码:

ws.update('A1', new_bs, value_input_option=gspread.utils.ValueInputOption.user_entered)

或者

ws.update('A1', new_bs, value_input_option="USER_ENTERED")

参考资料:

撰写回答