Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Google Timeline KML to working enter-exit
# parses KML from Google Timeline to obtain places
# Emanuele Ruffaldi 2018
import os,sys
import csv
import datetime
import xml.etree.ElementTree as ET
from collections import defaultdict
import time
from dateutil import tz
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
def iso2time(x):
return datetime.datetime.strptime(x, "%Y-%m-%dT%H:%M:%S.%fZ")
def dt2ts(dt):
return time.mktime(dt.timetuple())
def ts2dt(ts):
return datetime.datetime.fromtimestamp(ts)
def main():
pre = '{http://www.opengis.net/kml/2.2}'
out = csv.DictWriter(open("out.tsv","wb"),fieldnames=["place","start","end"],delimiter="\t")
out.writeheader()
byday = defaultdict(list)
for x in sys.argv[1:]:
if os.path.isdir(x):
q = [os.path.join(x,y) for y in os.listdir(x) if y.endswith(".kml")]
else:
q = [x]
for y in q:
print (y)
tree = ET.parse(y)
root = tree.getroot()
for p in root.find(pre+"Document").findall(pre+'Placemark'):
name = p.find(pre+"name").text
ts = p.find(pre+"TimeSpan")
tss = iso2time(ts.find(pre+"begin").text)
tse = iso2time(ts.find(pre+"end").text)
out.writerow(dict(place=name,start=tss,end=tse))
if name.find("Work") >= 0:
# TODO FIX time
# TODO detect change of dat for
byday[tss.date()].append((tss,tse))
#outjob
else:
print(name)
outjob = csv.DictWriter(open("outjob.tsv","wb"),fieldnames=["place","day","arrive","leave"],delimiter="\t")
outjob.writeheader()
for k,d in byday.items():
earliest = min([(x[0]) for x in d]).replace(tzinfo=from_zone).astimezone(to_zone)
latest = max([(x[1]) for x in d]).replace(tzinfo=from_zone).astimezone(to_zone)
print (k,earliest)
outjob.writerow(dict(place="Work",day=k,arrive=(earliest.strftime('%Y/%m/%d %H:%M')),leave=(latest.strftime('%Y/%m/%d %H:%M'))))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.