如何用Python 3.9编程获取Google Sheets的最后更新时间戳
获取Google Sheets最后更新时间戳的Python 3.9实现
要避免全量读取表格来判断更新,你可以通过Google的Drive API或Sheets API直接获取表格的最后修改时间戳,以下是两种可行的实现方案:
前置准备
- 启用对应API:在Google Cloud控制台创建项目,启用Google Sheets API和Google Drive API(根据选择的方案)。
- 配置服务账号:创建服务账号并下载密钥JSON文件,将该账号共享到目标Google Sheets表格(至少分配查看权限)。
方案1:通过Drive API获取修改时间
Drive API可直接读取文件元数据,无需加载表格内容,适合只需要文件级修改时间的场景。
安装依赖
pip install google-api-python-client oauth2client
代码实现
from google.oauth2.service_account import Credentials from googleapiclient.discovery import build from datetime import datetime # 定义API权限(仅需Drive元数据只读权限) SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'] # 加载服务账号密钥 creds = Credentials.from_service_account_file('your-service-account-key.json', scopes=SCOPES) def get_sheet_last_modified(sheet_id): # 初始化Drive API客户端 drive_service = build('drive', 'v3', credentials=creds) # 仅请求modifiedTime字段,减少数据传输量 file_metadata = drive_service.files().get(fileId=sheet_id, fields='modifiedTime').execute() # 转换为Python datetime对象(方便时间比较) modified_time_str = file_metadata['modifiedTime'] modified_time = datetime.fromisoformat(modified_time_str.replace('Z', '+00:00')) return modified_time # 使用示例 if __name__ == '__main__': target_sheet_id = 'your-google-sheet-id-here' last_update = get_sheet_last_modified(target_sheet_id) print(f"表格最后更新时间:{last_update}")
方案2:通过Sheets API获取修改时间
如果你只希望依赖Sheets API,可通过spreadsheets.get接口读取表格属性中的修改时间,权限更聚焦。
安装依赖
pip install google-api-python-client oauth2client
代码实现
from google.oauth2.service_account import Credentials from googleapiclient.discovery import build from datetime import datetime # 定义API权限(仅需Sheets只读权限) SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'] # 加载服务账号密钥 creds = Credentials.from_service_account_file('your-service-account-key.json', scopes=SCOPES) def get_sheet_last_modified_via_sheets(sheet_id): # 初始化Sheets API客户端 sheets_service = build('sheets', 'v4', credentials=creds) # 仅请求properties/modifiedTime字段 spreadsheet = sheets_service.spreadsheets().get( spreadsheetId=sheet_id, fields='properties/modifiedTime' ).execute() modified_time_str = spreadsheet['properties']['modifiedTime'] modified_time = datetime.fromisoformat(modified_time_str.replace('Z', '+00:00')) return modified_time # 使用示例 if __name__ == '__main__': target_sheet_id = 'your-google-sheet-id-here' last_update = get_sheet_last_modified_via_sheets(target_sheet_id) print(f"表格最后更新时间:{last_update}")
关键说明
- 权限验证:务必确保服务账号已被添加为目标表格的协作者,否则会触发权限错误。
- 时间比较:转换后的
datetime对象可直接与本地记录的上次更新时间对比,快速判断是否需要拉取新数据。 - 性能优化:两种方案都仅获取元数据,相比全量读取表格,能大幅降低请求耗时和带宽消耗。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

