-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimeline_parse.py
More file actions
147 lines (115 loc) · 5.18 KB
/
timeline_parse.py
File metadata and controls
147 lines (115 loc) · 5.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
from datetime import datetime, timedelta
import json
import os
import sys
import time
def iso_timestamp_to_datetime(iso_timestamp_string: str) -> datetime:
# The format from google may or may not have microseconds so check both
try:
return_date = datetime.strptime(
iso_timestamp_string, "%Y-%m-%dT%H:%M:%S.%f%z")
except:
return_date = datetime.strptime(
iso_timestamp_string, "%Y-%m-%dT%H:%M:%S%z")
# Determine the offset from UTC that the current timezone
date_now = time.time()
offset = datetime.fromtimestamp(
date_now) - datetime.utcfromtimestamp(date_now)
return return_date + offset
def time_difference_in_h_m_s(startTimestamp: datetime, endTimestamp: datetime):
duration_secs = float((
endTimestamp - startTimestamp).total_seconds())
d_hours = int(duration_secs / 3600.)
d_mins = int((duration_secs - (d_hours * 3600.)) / 60.)
d_secs = int(duration_secs -
(d_hours * 3600.) - (d_mins * 60.))
return d_hours, d_mins, d_secs
def getPlaceLocation(key, value):
location = ""
if value == "HOME":
location = "Assuming home"
else:
startTimestamp = iso_timestamp_to_datetime(
value["duration"]["startTimestamp"])
endTimestamp = iso_timestamp_to_datetime(
value["duration"]["endTimestamp"])
d_hours, d_mins, d_secs = time_difference_in_h_m_s(
startTimestamp, endTimestamp)
# Sometimes a place has a name, not an adress. Try name first, then adress
try:
location = value["location"]["name"]
except:
try:
location = value["location"]["address"].replace(
"\n", " ").replace(",", " ")
except:
# neither method worked! Help!
print(
f"Error- placeVisit did not have 'name' or 'address'! {value['location']}")
exit(4)
return location
def parse_google_timeline_json(filename: str, output_file_handle):
print(f"Parsing {filename}...")
with open(filename) as json_file:
# returns JSON object as
# a dictionary
# The google "Takeout" JSON file consists of items which are activitySegments (think: travel) or placeVisits (you can figure that one out!)
data = json.load(json_file)
print(f"{filename} read and parsed successfully.")
timeline_list = list(data["timelineObjects"])
item_count = len(timeline_list)
for i in range(0, item_count - 1):
# There is no record before the first one
if i == 0:
prev_key = "placeVisit"
prev_value = "HOME"
else:
prev_key = list(timeline_list[i-1])[0]
prev_value = list(timeline_list[i-1].values())[0]
key0 = list(timeline_list[i])[0]
value0 = list(timeline_list[i].values())[0]
next_key = list(timeline_list[i+1])[0]
next_value = list(timeline_list[i+1].values())[0]
if key0 == "activitySegment":
startTimestamp = iso_timestamp_to_datetime(
value0["duration"]["startTimestamp"])
endTimestamp = iso_timestamp_to_datetime(
value0["duration"]["endTimestamp"])
activityType = value0["activityType"]
try:
distance_m = value0["distance"]
except:
print(
f"WARNING! activitySegment did not have a 'distance'! {value0}. Assuming 0 km?")
distance_m = 0
d_hours, d_mins, d_secs = time_difference_in_h_m_s(
startTimestamp, endTimestamp)
if activityType == "IN_PASSENGER_VEHICLE" and prev_key == "placeVisit" and next_key == "placeVisit":
prev_location = getPlaceLocation(prev_key, prev_value)
next_location = getPlaceLocation(next_key, next_value)
output_file_handle.write(
f'"{prev_location}","{next_location}",{startTimestamp:%d/%m/%Y %H:%M:%S},{endTimestamp:%d/%m/%Y %H:%M:%S},{distance_m/1000.}\n')
print(
f"{activityType} from: {prev_location} to {next_location} at time {startTimestamp} to {endTimestamp} ({d_hours}h {d_mins}m {d_secs}s) {distance_m} m")
elif key0 == "placeVisit":
pass
else:
print("No idea how to process {key0}")
exit(3)
if __name__ == "__main__":
# Get command line args
if len(sys.argv) == 2:
filename = sys.argv[1]
# Does the file exist?
if not os.path.exists(filename):
print(f"Error: {filename} does not exist!")
exit(2)
# open csv for output
output_filename = "output.csv"
with open(output_filename, "w") as output_file_handle:
# ok, let's do the parsing
parse_google_timeline_json(filename, output_file_handle)
print(f"CSV written to {output_filename}. I'm done!")
else:
print("Usage: \npython timeline_parse.py GOOGLE_JSON_FILENAME\n")
exit(1)