Skip to content

Instantly share code, notes, and snippets.

@mlindgren
Created January 24, 2020 00:21
Show Gist options
  • Save mlindgren/c313f6daea6e7ddbbf321986552ef564 to your computer and use it in GitHub Desktop.
Save mlindgren/c313f6daea6e7ddbbf321986552ef564 to your computer and use it in GitHub Desktop.
Script to fix distance for indoor cycling activities in TCX files exported from Garmin Connect
import argparse
import datetime
import xml.etree.ElementTree as ET
# To do: should set this up dynamically from the xmlns in the file
ns = {'tcx' : "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2"}
time_format = '%Y-%m-%dT%H:%M:%S.000Z'
parser = argparse.ArgumentParser(description = "Recalculate distance in TCX file for indoor activities")
parser.add_argument("file", type = argparse.FileType('r'), help = "Input TCX file")
parser.add_argument("distance", type = int, help = "Distance in meters")
args = parser.parse_args()
# print(args)
tree = ET.parse(args.file)
activities = tree.getroot().find('tcx:Activities', ns)
activity = activities.find('tcx:Activity', ns)
lap = activity.find('tcx:Lap', ns)
start_time = datetime.datetime.strptime(lap.attrib['StartTime'], time_format)
duration = datetime.timedelta(seconds = float(lap.find('tcx:TotalTimeSeconds', ns).text))
end_time = start_time + duration
lap_distance = lap.find('tcx:DistanceMeters', ns)
lap_distance.text = str(args.distance)
track = lap.find('tcx:Track', ns)
trackpoints = track.findall('tcx:Trackpoint', ns)
for point in trackpoints:
current_time = datetime.datetime.strptime(point.find('tcx:Time', ns).text, time_format)
current_duration = current_time - start_time
duration_completed = current_duration / duration
distance_so_far = point.find('tcx:DistanceMeters', ns)
distance_so_far.text = str(duration_completed * args.distance)
tree.write('out.tcx')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment