Created
February 5, 2026 15:47
-
-
Save elnjensen/8ac4a32e02770d4fff64595b9b436579 to your computer and use it in GitHub Desktop.
Use Python gspread fetch Google Sheet only if newer than a certain date or file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| # Example showing how to check the last-modified time of a Google | |
| # Sheet using gspread, and compare it to a local file's modification | |
| # time. This uses the Google Drive API (via gspread's built-in | |
| # get_file_drive_metadata method) rather than the Sheets API, since | |
| # the Sheets API doesn't expose file modification times. | |
| # | |
| # The same service account credentials used for gspread authentication | |
| # work for the Drive API call with no additional setup. | |
| # | |
| # Requires: gspread (pip install gspread) | |
| # Authentication: uses gspread.service_account(), which looks for | |
| # a service account JSON key file. See the gspread docs for setup: | |
| # https://docs.gspread.org/en/latest/oauth2.html | |
| import sys | |
| import os | |
| from datetime import datetime, timezone | |
| import gspread | |
| SPREADSHEET_NAME = "My Spreadsheet Name" | |
| def main(): | |
| gc = gspread.service_account() | |
| sh = gc.open(SPREADSHEET_NAME) | |
| # get_file_drive_metadata calls the Drive API and returns a dict | |
| # with keys: id, name, createdTime, modifiedTime | |
| metadata = gc.get_file_drive_metadata(sh.id) | |
| sheet_modified_str = metadata["modifiedTime"] | |
| # Parse the ISO 8601 timestamp (e.g. "2025-02-04T15:33:36.140Z") | |
| sheet_modified = datetime.fromisoformat( | |
| sheet_modified_str.replace("Z", "+00:00")) | |
| print(f"Spreadsheet last modified: {sheet_modified}") | |
| # If a local filename was given on the command line, compare | |
| # its modification time to the spreadsheet's. | |
| if len(sys.argv) > 1: | |
| local_file = sys.argv[1] | |
| if not os.path.exists(local_file): | |
| print(f"Local file '{local_file}' does not exist.") | |
| sys.exit(1) | |
| file_mtime = os.path.getmtime(local_file) | |
| file_modified = datetime.fromtimestamp(file_mtime, | |
| tz=timezone.utc) | |
| print(f"Local file last modified: {file_modified}") | |
| if sheet_modified > file_modified: | |
| print("Spreadsheet is newer than local file.") | |
| # Add code to fetch remote file if desired. | |
| else: | |
| print("Local file is up to date.") | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment