Skip to content

Instantly share code, notes, and snippets.

@sitz
Forked from devdattaT/ConvertGoogleHistory.py
Last active February 7, 2025 09:45
Show Gist options
  • Save sitz/024bbbaf5eedc579bd7ce8fb885a41bb to your computer and use it in GitHub Desktop.
Save sitz/024bbbaf5eedc579bd7ce8fb885a41bb to your computer and use it in GitHub Desktop.
import json
import csv
import sys
from datetime import datetime
import os
def make_reader(in_json):
# Open location history data
json_data = json.loads(open(in_json).read())
for segment in json_data['semanticSegments']:
if 'visit' in segment:
latitude, longitude = segment['visit']['topCandidate']['placeLocation']['latLng'].replace('°', '').split(', ')
time = datetime.strptime(segment['startTime'], '%Y-%m-%dT%H:%M:%S.%f%z')
yield [time.isoformat(), float(longitude), float(latitude)]
if 'activity' in segment:
for type in ['start', 'end']:
latitude, longitude = segment['activity'][type]['latLng'].replace('°', '').split(', ')
time = datetime.strptime(segment[f'{type}Time'], '%Y-%m-%dT%H:%M:%S.%f%z')
yield [time.isoformat(), float(longitude), float(latitude)]
if 'position' in segment:
latitude, longitude = segment['LatLng'].replace('°', '').split(', ')
time = datetime.strptime(segment['timestamp'], '%Y-%m-%dT%H:%M:%S.%f%z')
yield [time.isoformat(), float(longitude), float(latitude)]
if 'timelinePath' in segment:
for point in segment['timelinePath'][:1]:
latitude, longitude = point['point'].replace('°', '').split(', ')
time = datetime.strptime(point['time'], '%Y-%m-%dT%H:%M:%S.%f%z')
yield [time.isoformat(), float(longitude), float(latitude)]
def getFullPath(inPath):
if not os.path.isabs(inPath):
script_path = os.path.abspath(__file__)
path, file = os.path.split(script_path)
inPath = os.path.join(path, inPath)
return inPath
# Read i/o file names
input_file = 'location-history.json'
output_file = 'location-history.csv'
# Read data from JSON file
reader = make_reader(input_file)
# Add the Headers
features = [['Time', 'Longitude', 'Latitude']]
for row in reader:
features.append(row)
# Write data to CSV file
writer = csv.writer(open(output_file, 'w', newline=''))
writer.writerows(features)
@MadsFich
Copy link

MadsFich commented Jan 8, 2025

getting this error. do you have an idea?

Traceback (most recent call last):
File ConvertGoogleHistory.py", line 52, in
for row in reader:
File ConvertGoogleHistory.py", line 33, in make_reader
yield [time.isoformat(), float(longitude), float(latitude)]
ValueError: could not convert string to float: '12.0679108Â'

@Gunslap
Copy link

Gunslap commented Jan 13, 2025

getting this error. do you have an idea?

Traceback (most recent call last): File ConvertGoogleHistory.py", line 52, in for row in reader: File ConvertGoogleHistory.py", line 33, in make_reader yield [time.isoformat(), float(longitude), float(latitude)] ValueError: could not convert string to float: '12.0679108Â'

I got that error as well. For some reason it's seeing a "Â" character in the long + lat data before the degree sign. Not sure why that's the case. If you add lines to remove that character from both the long and lat in each segment type (vist, activity, position, and timelinePath) after the long+lat are created it will then work.

ie:
if 'visit' in segment:
latitude, longitude = segment['visit']['topCandidate']['placeLocation']['latLng'].replace('°', '').split(', ')
latitude = latitude.replace('Â', '')
longitude = longitude.replace('Â', '')

@korjavin
Copy link

Worked as charm, thank you as lot.

@fab343
Copy link

fab343 commented Feb 7, 2025

@sitz I get this error

KeyError: 'semanticSegments'

my json file from google takeout from yesterday looks like this:
` "deviceId": "XXXXXXX",

"rawSignal": {
  "signal": {
    "position": {
      "point": {
        "latE7": 4XXX9000302,
        "lngE7": 1XXX4936499
      },
      "accuracyMm": 172000,
      "altitudeMeters": 93.0,
      "source": "GPS",
      "timestamp": "2024-02-29T14:11:32.692Z"
    }
  },
  "additionalTimestamp": "2024-02-29T14:28:05.610Z",
  "metadata": {
    "platform": "ANDROID"`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment