Search code examples
pythonpython-3.xgoogle-sheetsgspread

Python - How to check if a Google Spreadsheets was updated


I needed to check if there was an update to the shared Google Spreadsheets document. I thought of bringing the field "Last edit was made on September 15 by Rob" as a date or as a timestamp in Python and check if the difference was less than a day, but I didn't find anything in the documentation about that.

My code so far:

from oauth2client.service_account import ServiceAccountCredentials
import gspread
import pandas as pd

def get_gsheet_table(url, sheet_name):

    scope = ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/spreadsheets"]
    credentials = ServiceAccountCredentials.from_json_keyfile_name('./credentials/get_sheet_table.json', scope)
    gc = gspread.authorize(credentials)

    wb = gc.open_by_url(url)
    sheet = wb.worksheet(sheet_name)
    
    #TODO: check if there was an update

    data = sheet.get_all_values()
    df = pd.DataFrame(data)

    df.columns = df.iloc[0]
    df = df.iloc[1:]
    return df

I'm trying to do this way of taking the date out of the document because I didn't want to need to make a backup spreadsheet and compare the two.

Any suggestions are welcome


Solution

  • Thanks to the help of Tanaike with the link to the documentation, I was able to solve the problem.

    Here is the code:

    import requests
    
    revisions_uri = f'https://www.googleapis.com/drive/v3/files/{wb.id}/revisions'
        headers = {'Authorization': f'Bearer {credentials.get_access_token().access_token}'}
        response = requests.get(revisions_uri, headers=headers).json()
        print(response['revisions'][-1]['modifiedTime'])