Last active
December 21, 2022 21:58
-
-
Save lachiefish/5837c0ec263aa956acc92963d9ef0d8e to your computer and use it in GitHub Desktop.
Converts a Google Timeline export JSON file into a GPX file to be used with other applications. The JSON file is in the same directory as the python script and is named timeline.json. Try blocks are because Google has used different time formats over the years.
This file contains 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
import json | |
import datetime | |
# Open the JSON file | |
with open('timeline.json') as f: | |
data = json.load(f) | |
# Open a new GPX file for writing | |
with open('timeline.gpx', 'w') as gpx_file: | |
# Write the GPX file header | |
gpx_file.write('<?xml version="1.0" encoding="UTF-8"?>\n') | |
gpx_file.write('<gpx version="1.1" creator="My GPS Track">\n') | |
# Iterate through the timeline entries in the JSON file | |
for entry in data['locations']: | |
# Extract the latitude and longitude from the entry | |
lat = entry['latitudeE7'] / 1e7 | |
lon = entry['longitudeE7'] / 1e7 | |
# Convert the timestamp to the timestampMs format | |
timestamp = entry['timestamp'] | |
try: | |
# Try parsing the timestamp using the first format string | |
dt = datetime.datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.%fZ') | |
except ValueError: | |
# If the first format string fails, try the second format string | |
try: | |
# If the first format string fails, try the second format string | |
dt = datetime.datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S:%fZ') | |
except ValueError: | |
# If the second format string fails, try the third format string | |
dt = datetime.datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%SZ') | |
timestamp_ms = int(dt.timestamp()) * 1000 | |
# Write the location data to the GPX file | |
gpx_file.write(f' <wpt lat="{lat}" lon="{lon}">\n') | |
gpx_file.write(f' <time>{timestamp_ms}</time>\n') | |
gpx_file.write(' </wpt>\n') | |
# Write the GPX file footer | |
gpx_file.write('</gpx>\n') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment