Skip to content

Instantly share code, notes, and snippets.

@StevenMaude
Last active March 15, 2016 00:42
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 StevenMaude/883fdd4db9f5a8688d11 to your computer and use it in GitHub Desktop.
Save StevenMaude/883fdd4db9f5a8688d11 to your computer and use it in GitHub Desktop.
Quick hacky script to extract date and 2D length data from GPX files to CSV using gpxpy; at least compatible with Py2.7/3.4
#!/usr/bin/env python
""" Extract date and 2D length data from GPX files in current directory. """
from __future__ import division, print_function
import decimal
import glob
import gpxpy
def main():
gpx_filenames = glob.glob("*.gpx")
print("Filename,Date (YYYY-MM-DD),Time,"
"Length (km),ISO year,ISO week number")
for gpx_filename in gpx_filenames:
with open(gpx_filename, 'r') as f:
gpx = gpxpy.parse(f.read())
for track in gpx.tracks:
extract_track_data(track, gpx_filename)
def extract_track_data(track, gpx_filename):
""" Take GPX track and string filename; print comma separated data. """
start_datetime, _ = track.get_time_bounds()
iso_year, iso_week_number, _ = start_datetime.isocalendar()
km_2d_length = decimal.Decimal(track.length_2d()/1000)
output = ','.join([gpx_filename,
str(start_datetime.date()),
str(start_datetime.time()),
str(round(km_2d_length, 2)),
str(iso_year),
str(iso_week_number)])
print(output)
if __name__ == '__main__':
main()
@StevenMaude
Copy link
Author

TODO: maybe do the counting of data I want in this script, rather than using Pivot Tables in LibreOffice; or maybe using Jupyter is a better solution.

(My current use of this is finding out my total run distance per week — which is a Pivot Table of ISO week number and ISO year with sum of length as data — and the number of days I've run, which is a Pivot Table of ISO week number with unique count of date as data; this is generated separately using COUNTIF via https://stackoverflow.com/questions/11876238/simple-pivot-table-to-count-unique-values and ISO week number/count of unique count as data.) That works but is messing you have to do after extraction, which suggests doing it all in Python is nicer.

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