Skip to content

Instantly share code, notes, and snippets.

@kreed
Last active January 23, 2020 04:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kreed/db57e26ba2c2252c3c1cf471caa8ed44 to your computer and use it in GitHub Desktop.
Save kreed/db57e26ba2c2252c3c1cf471caa8ed44 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# Usage: ./tcx_dist.py [input.tcx] [new distance in meters]
# Override distance of track points in TCX with new overall distance
from time import strptime, strftime
import xml.etree.ElementTree as ET
import sys
import re
infile = open(sys.argv[1])
new_dist = float(sys.argv[2])
if new_dist < 50:
new_dist = new_dist * 1609.34
def get_time(e):
timestamp = e.find('{http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2}Time').text
return int(strftime('%s', strptime(timestamp, '%Y-%m-%dT%H:%M:%S.000Z')))
ET.register_namespace('', "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2")
tcx = ET.fromstring(infile.read())
activity = tcx.find('.//{http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2}Activity').attrib['Sport']
start_seconds = get_time(tcx.findall('.//{http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2}Trackpoint')[0])
end_seconds = get_time(tcx.findall('.//{http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2}Trackpoint')[-1])
total_seconds = end_seconds - start_seconds
for point in tcx.findall('.//{http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2}Trackpoint'):
seconds = get_time(point)
percent = (seconds - start_seconds) / total_seconds
dist_fixed = new_dist * percent
point.find('{http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2}DistanceMeters').text = str(dist_fixed)
with open('out.tcx', 'w') as f:
f.write('<?xml version="1.0" encoding="UTF-8"?>\n')
f.write(ET.tostring(tcx, encoding='unicode'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment