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

如何获取公开分享的Google Doc/Sheet等文件的最后修改时间?

公开Google Drive文件(Sheet/Doc/Colab)免API获取最后修改时间方案

不需要调用Google Drive API、不需要注册密钥或OAuth认证,公开共享的文件可以直接通过响应头拿到最后修改时间,具体实现逻辑如下:

实现步骤

  • 第一步:从共享链接提取文件ID
    标准的Google文件共享链接格式一般为https://docs.google.com/[类型]/d/[文件ID]/[后续参数],提取d/和下一个/之间的字符串即为文件ID。
  • 第二步:发送HEAD请求获取响应头
    公开共享文件的响应头中包含X-Goog-Drive-File-Modified-Time字段,即为文件的最后修改时间,使用HEAD请求无需下载文件本体,仅获取头信息,效率极高。

Python实现示例

首先安装依赖库:
pip install requests

完整脚本参考:

import requests
import os
from datetime import datetime

def get_google_file_modified_time(file_id: str) -> datetime:
    # 通用公开文件端点,无需认证
    url = f"https://drive.google.com/uc?id={file_id}"
    # 发送HEAD请求仅获取响应头
    response = requests.head(url, allow_redirects=True)
    # 提取修改时间字段并转为datetime对象
    modified_time_str = response.headers.get("X-Goog-Drive-File-Modified-Time")
    if not modified_time_str:
        raise Exception("无法获取修改时间,请确认文件共享权限为「任何人可查看」")
    return datetime.strptime(modified_time_str, "%a, %d %b %Y %H:%M:%S %Z")

def is_remote_newer(file_id: str, local_file_path: str) -> bool:
    # 本地文件不存在时默认远程更新
    if not os.path.exists(local_file_path):
        return True
    # 获取本地文件最后修改时间并转为UTC时间
    local_mtime = datetime.utcfromtimestamp(os.path.getmtime(local_file_path))
    remote_mtime = get_google_file_modified_time(file_id)
    return remote_mtime > local_mtime

# 使用示例
if __name__ == "__main__":
    # 替换为实际的文件ID和本地存储路径
    TARGET_FILE_ID = "你的文件ID"
    LOCAL_SAVE_PATH = "./本地存储文件名.xlsx"
    
    if is_remote_newer(TARGET_FILE_ID, LOCAL_SAVE_PATH):
        print("远程文件更新,开始下载")
        # 下载逻辑,需要导出特定格式可以调整url参数
        download_r = requests.get(
            f"https://drive.google.com/uc?id={TARGET_FILE_ID}&export=download",
            allow_redirects=True
        )
        with open(LOCAL_SAVE_PATH, "wb") as f:
            f.write(download_r.content)
    else:
        print("本地文件已是最新版本,无需下载")

注意事项

  • 请确保文件的共享权限设置为「知道链接的任何人都可以查看」,否则无法正常获取响应头字段
  • 如果是需要导出为特定格式(比如Sheet导出为xlsx、Doc导出为docx),下载时可以在url中添加format=[格式后缀]参数调整导出格式
  • 该方案对Google Sheet、Google Doc、Colab Notebook、普通存储在Drive的公开文件均适用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 22:48:02