Skip to content

Instantly share code, notes, and snippets.

@seongyooncho
Created February 23, 2025 06:26
Show Gist options
  • Select an option

  • Save seongyooncho/2709800a2a83c5a425fafb135cf970bf to your computer and use it in GitHub Desktop.

Select an option

Save seongyooncho/2709800a2a83c5a425fafb135cf970bf to your computer and use it in GitHub Desktop.
Extract body weight from Apple Health Export and save to csv.
import xml.etree.ElementTree as ET
import csv
from datetime import datetime
def export_body_mass_to_csv(xml_file, csv_file):
context = ET.iterparse(xml_file, events=("end",))
with open(csv_file, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['Date', 'Weight'])
count = 0
for event, elem in context:
if elem.tag == "Record" and elem.get("type") == "HKQuantityTypeIdentifierBodyMass":
date_str = elem.get("creationDate")
weight = elem.get("value")
# Parse the date string and convert it to ISO 8601 format.
try:
dt = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S %z")
formatted_date = dt.isoformat() # e.g., 2017-09-26T18:30:11+09:00
except Exception as e:
formatted_date = date_str # Fallback in case of parsing error
writer.writerow([formatted_date, weight])
count += 1
if count % 1000 == 0:
print(f"Processed {count} records...")
elem.clear()
print(f"Finished processing {count} records.")
if __name__ == '__main__':
export_body_mass_to_csv('export.xml', 'body_mass.csv')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment