bicycle-statistics/gpx_parser/__init__.py

83 lines
2.9 KiB
Python
Raw Normal View History

import datetime
import glob
import os
import gpxpy
import gpxpy.gpx
from geopy import distance
from geopy import Point
class Segment(object):
start_time = None
end_time = None
distance = 0.0 # [m]
class Track(object):
start_time = None
end_time = None
distance = 0.0 # [m]
avg_speed = 0.0 # [km/h]
duration = None
def __init__(self, raw_track):
self.__raw = raw_track
for segment in self.__raw.segments:
seg = Segment()
for i in range(1, len(segment.points)):
if self.start_time is None:
self.start_time = segment.points[i - 1].time
if seg.start_time is None:
seg.start_time = segment.points[i - 1].time
seg.end_time = segment.points[i - 1].time
point1 = Point(str(segment.points[i - 1].latitude) + \
' ' + str(segment.points[i - 1].longitude))
point2 = Point(str(segment.points[i].latitude) + \
' ' + str(segment.points[i].longitude))
seg.distance += distance.distance(point1, point2).meters
if self.duration is None:
self.duration = seg.end_time - seg.start_time
else:
self.duration += seg.end_time - seg.start_time
self.end_time = seg.end_time
self.distance += seg.distance
self.avg_speed = self.distance / self.duration.total_seconds() * 3.6
class Tracks(object):
track_list = None
def __init__(self, folder):
self.track_list = list()
gpx_list = glob.glob(os.path.join(folder, '*.gpx'))
for entry in gpx_list:
with open(entry, 'r') as gpx_handle:
gpx = gpxpy.parse(gpx_handle)
for raw_track in gpx.tracks:
self.track_list.append(Track(raw_track))
def get(self, year='all', month='all', day='all'):
ret = list()
if year == 'all':
ret = self.track_list
elif month == 'all':
pick_date = datetime.datetime(year=year, month=1, day=1)
for entry in self.track_list:
if pick_date.year == entry.start_time.year:
ret.append(entry)
elif day == 'all':
pick_date = datetime.datetime(year=year, month=month, day=1)
ret = list()
for entry in self.track_list:
if pick_date.year == entry.start_time.year and \
pick_date.month == entry.start_time.month:
ret.append(entry)
else:
pick_date = datetime.datetime(year=year, month=month, day=day)
ret = list()
for entry in self.track_list:
if pick_date.year == entry.start_time.year and \
pick_date.month == entry.start_time.month and \
pick_date.day == entry.start_time.day:
ret.append(entry)
return ret