Skip to content

Instantly share code, notes, and snippets.

@Nempickaxe
Created April 19, 2023 09:34
Show Gist options
  • Save Nempickaxe/1966f615f744dd51ddf5a632212a7afd to your computer and use it in GitHub Desktop.
Save Nempickaxe/1966f615f744dd51ddf5a632212a7afd to your computer and use it in GitHub Desktop.
download google fit data through GCP project enabling fitness API
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from datetime import datetime, timedelta
import pandas as pd
from google_auth_oauthlib.flow import InstalledAppFlow
# Replace with the path to your credentials.json file
credentials_path = 'fitternew.json'
# Define the scopes that your app needs
SCOPES = ['https://www.googleapis.com/auth/fitness.activity.read']
# Create a flow object to handle the OAuth 2.0 authorization process
flow = InstalledAppFlow.from_client_secrets_file(
credentials_path,
scopes=SCOPES,
redirect_uri='urn:ietf:wg:oauth:2.0:oob'
)
# Start the authorization flow and get the authorization URL
auth_url, _ = flow.authorization_url(access_type='offline')
# Print the authorization URL and prompt the user to visit it
print(f"Visit this URL to authorize the application: {auth_url}")
auth_code = input("Enter the authorization code: ")
# Exchange the authorization code for a set of access and refresh tokens
flow.fetch_token(code=auth_code)
# Get the credentials object from the flow object
creds = flow.credentials
# Use the credentials object to make authorized requests to the API
# set up Google Fit API client
fit_client = build('fitness', 'v1', credentials=creds)
# define date range for step data to download
end_date = datetime.utcnow()
start_date = end_date - timedelta(days=500) # last 365 days
# make requests for each 90-day chunk of data
step_data = []
while end_date > start_date:
request_end_date = end_date
request_start_date = request_end_date - timedelta(days=90) # 90-day chunk
if request_start_date < start_date:
request_start_date = start_date
# set up request to retrieve step data from Google Fit API
request = fit_client.users().dataset().aggregate(userId='me', body={
"aggregateBy": [{
"dataTypeName": "com.google.step_count.delta",
"dataSourceId": "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps"
}],
"bucketByTime": { "durationMillis": 86400000*7 },
"startTimeMillis": int(request_start_date.timestamp()) * 1000,
"endTimeMillis": int(request_end_date.timestamp()) * 1000,
})
# execute request and retrieve step data
response = request.execute()
# extract step data from response
if 'bucket' in response:
for bucket in response['bucket']:
if 'dataset' in bucket:
for dataset in bucket['dataset']:
if 'point' in dataset:
for point in dataset['point']:
if 'value' in point:
step_count = point['value'][0]['intVal']
timestamp = int(point['endTimeNanos']) / 1000000
date = datetime.utcfromtimestamp(timestamp / 1000).strftime('%Y-%m-%d')
step_data.append({'date': date, 'timestamp': timestamp, 'step_count': step_count})
# update end_date for next iteration
end_date = request_start_date
# print step data
print(step_data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment