Last active
January 28, 2021 22:17
-
-
Save timster/b6c31bed399b89ffda82b781e2b0cb7f to your computer and use it in GitHub Desktop.
Parsing apple health data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import datetime | |
from collections import namedtuple | |
from lxml import etree | |
EXPORT_FILE = 'apple_health_export/export.xml' | |
BodyMass = namedtuple('BodyMass', ('date_time', 'value')) | |
StepCount = namedtuple('StepCount', ('date_time', 'value')) | |
Distance = namedtuple('Distance', ('date_time', 'value')) | |
Stairs = namedtuple('Stairs', ('date_time', 'value')) | |
TYPE_MAP = { | |
'HKQuantityTypeIdentifierBodyMass': BodyMass, | |
'HKQuantityTypeIdentifierStepCount': StepCount, | |
'HKQuantityTypeIdentifierDistanceWalkingRunning': Distance, | |
'HKQuantityTypeIdentifierFlightsClimbed': Stairs, | |
} | |
UNIT_MAP = { | |
'km': 0.621371, # kilometer to miles | |
'kg': 2.20462, # kilograms to pounds | |
} | |
def parse_record(record): | |
item_class = TYPE_MAP.get(record.get('type')) | |
if not item_class: | |
return | |
value = record.get('value') | |
multiplier = UNIT_MAP.get(record.get('unit')) | |
if multiplier: | |
value = value * multiplier | |
parsed_date = datetime.strptime(record.get('creationDate'), '%Y-%m-%d %H:%M:%S %z') | |
yield item_class(date_time=parsed_date, value=value) | |
def parse(file_like_object): | |
doc = etree.parse(file_like_object) | |
for record in doc.iter('Record'): | |
yield from parse_record(record) | |
if __name__ == '__main__': | |
with open(EXPORT_FILE, 'r') as handle: | |
for item in parse(handle): | |
print(item) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment