├── tests ├── __init__.py ├── zip_contents │ ├── sedentary_minutes.json │ ├── very_active_minutes.json │ ├── lightly_active_minutes.json │ ├── moderately_active_minutes.json │ ├── sleep_score.csv │ ├── distance.json │ ├── resting_heart_rate.json │ ├── heart_rate_zones.json │ ├── sleep.json │ └── exercise.json ├── utils.py ├── test_create_zip.py ├── test_sedentary_minutes.py ├── test_very_active_minutes.py ├── test_resting_heart_rates.py ├── test_lightly_active_minutes.py ├── test_moderately_active_minutes.py ├── test_heart_rate_zones.py ├── test_distances.py ├── test_sleep_scores.py ├── test_sleep.py └── test_exercise.py ├── fitbit_to_sqlite ├── __init__.py ├── cli.py └── utils.py ├── .gitignore ├── setup.py ├── README.md └── LICENSE /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /fitbit_to_sqlite/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.db 2 | *.zip 3 | *.twb 4 | .DS_Store 5 | .venv 6 | tmp/* 7 | build/* 8 | dist/* 9 | __pycache__/ 10 | *.py[cod] 11 | *$py.class 12 | venv 13 | .eggs 14 | .pytest_cache 15 | *.egg-info 16 | 17 | -------------------------------------------------------------------------------- /tests/zip_contents/sedentary_minutes.json: -------------------------------------------------------------------------------- 1 | [{ 2 | "dateTime" : "01/01/18 00:00:00", 3 | "value" : "600" 4 | },{ 5 | "dateTime" : "01/02/18 00:00:00", 6 | "value" : "728" 7 | },{ 8 | "dateTime" : "01/03/18 00:00:00", 9 | "value" : "753" 10 | }] -------------------------------------------------------------------------------- /tests/zip_contents/very_active_minutes.json: -------------------------------------------------------------------------------- 1 | [{ 2 | "dateTime" : "01/01/18 00:00:00", 3 | "value" : "33" 4 | },{ 5 | "dateTime" : "01/02/18 00:00:00", 6 | "value" : "59" 7 | },{ 8 | "dateTime" : "01/03/18 00:00:00", 9 | "value" : "42" 10 | }] -------------------------------------------------------------------------------- /tests/zip_contents/lightly_active_minutes.json: -------------------------------------------------------------------------------- 1 | [{ 2 | "dateTime" : "01/01/18 00:00:00", 3 | "value" : "266" 4 | },{ 5 | "dateTime" : "01/02/18 00:00:00", 6 | "value" : "165" 7 | },{ 8 | "dateTime" : "01/03/18 00:00:00", 9 | "value" : "160" 10 | }] -------------------------------------------------------------------------------- /tests/zip_contents/moderately_active_minutes.json: -------------------------------------------------------------------------------- 1 | [{ 2 | "dateTime" : "01/01/18 00:00:00", 3 | "value" : "22" 4 | },{ 5 | "dateTime" : "01/02/18 00:00:00", 6 | "value" : "17" 7 | },{ 8 | "dateTime" : "01/03/18 00:00:00", 9 | "value" : "13" 10 | }] -------------------------------------------------------------------------------- /tests/zip_contents/sleep_score.csv: -------------------------------------------------------------------------------- 1 | sleep_log_entry_id,timestamp,overall_score,composition_score,revitalization_score,duration_score,deep_sleep_in_minutes,resting_heart_rate,restlessness 2 | 23644226806,2019-08-29T06:30:30Z,75,18,20,37,77,59,0.070093458 3 | 23561557819,2019-08-22T06:15:30Z,82,21,22,39,71,56,0.082497213 4 | -------------------------------------------------------------------------------- /tests/utils.py: -------------------------------------------------------------------------------- 1 | import zipfile 2 | import pathlib 3 | import io 4 | 5 | 6 | def create_zip(path=None): 7 | path = path or pathlib.Path(__file__).parent / "zip_contents" 8 | zf = zipfile.ZipFile(io.BytesIO(), "w") 9 | for filepath in path.glob("**/*"): 10 | if filepath.is_file(): 11 | zf.write(filepath, str(filepath.relative_to(path))) 12 | return zf 13 | -------------------------------------------------------------------------------- /tests/zip_contents/distance.json: -------------------------------------------------------------------------------- 1 | [{ 2 | "dateTime" : "12/31/17 16:42:00", 3 | "value" : "4110" 4 | },{ 5 | "dateTime" : "12/31/17 16:43:00", 6 | "value" : "4340" 7 | },{ 8 | "dateTime" : "12/31/17 16:44:00", 9 | "value" : "3490" 10 | },{ 11 | "dateTime" : "12/31/17 16:45:00", 12 | "value" : "850" 13 | },{ 14 | "dateTime" : "12/31/17 16:46:00", 15 | "value" : "0" 16 | }] -------------------------------------------------------------------------------- /tests/zip_contents/resting_heart_rate.json: -------------------------------------------------------------------------------- 1 | [{ 2 | "dateTime" : "12/30/18 00:00:00", 3 | "value" : { 4 | "date" : "12/30/18", 5 | "value" : 59.420772552490234, 6 | "error" : 6.787134170532227 7 | } 8 | },{ 9 | "dateTime" : "12/31/18 00:00:00", 10 | "value" : { 11 | "date" : "12/31/18", 12 | "value" : 58.29636573791504, 13 | "error" : 6.787102699279785 14 | } 15 | }] -------------------------------------------------------------------------------- /tests/test_create_zip.py: -------------------------------------------------------------------------------- 1 | import pathlib 2 | from .utils import create_zip 3 | 4 | 5 | def test_create_zip(): 6 | zf = create_zip() 7 | assert { 8 | "resting_heart_rate.json", 9 | "distance.json", 10 | "sedentary_minutes.json", 11 | "lightly_active_minutes.json", 12 | "moderately_active_minutes.json", 13 | "very_active_minutes.json", 14 | "exercise.json", 15 | "sleep.json", 16 | "sleep_score.csv", 17 | "heart_rate_zones.json", 18 | } == {f.filename for f in zf.filelist} 19 | -------------------------------------------------------------------------------- /tests/zip_contents/heart_rate_zones.json: -------------------------------------------------------------------------------- 1 | [{ 2 | "dateTime" : "01/02/18 00:00:00", 3 | "value" : { 4 | "valuesInZones" : { 5 | "IN_DEFAULT_ZONE_1" : 154.0, 6 | "IN_DEFAULT_ZONE_2" : 20.0, 7 | "IN_DEFAULT_ZONE_3" : 10.0, 8 | "BELOW_DEFAULT_ZONE_1" : 1037.0 9 | } 10 | } 11 | },{ 12 | "dateTime" : "04/11/18 00:00:00", 13 | "value" : { 14 | "valuesInZones" : { 15 | "IN_DEFAULT_ZONE_1" : 115.0, 16 | "BELOW_DEFAULT_ZONE_1" : 1239.0, 17 | "IN_DEFAULT_ZONE_3" : 0.0, 18 | "IN_DEFAULT_ZONE_2" : 0.0 19 | } 20 | } 21 | }] -------------------------------------------------------------------------------- /tests/test_sedentary_minutes.py: -------------------------------------------------------------------------------- 1 | from fitbit_to_sqlite.utils import save_sedentary_minutes 2 | import pathlib 3 | import sqlite_utils 4 | from .utils import create_zip 5 | 6 | 7 | def test_sedentary_minutes(): 8 | zf = create_zip() 9 | db = sqlite_utils.Database(memory=True) 10 | sedentary_minutes = [ 11 | f.filename for f in zf.filelist if "sedentary" in f.filename 12 | ] 13 | save_sedentary_minutes(db, zf, sedentary_minutes) 14 | sedentary_minutes = list(sorted(db["sedentary_minutes"].rows, key=lambda r: r["date"])) 15 | assert [ 16 | { 17 | "date": "2018-01-01", 18 | "value": 600 19 | }, 20 | { 21 | "date": "2018-01-02", 22 | "value": 728 23 | }, 24 | { 25 | "date": "2018-01-03", 26 | "value": 753 27 | } 28 | ] == sedentary_minutes 29 | -------------------------------------------------------------------------------- /tests/test_very_active_minutes.py: -------------------------------------------------------------------------------- 1 | from fitbit_to_sqlite.utils import save_very_active_minutes 2 | import pathlib 3 | import sqlite_utils 4 | from .utils import create_zip 5 | 6 | 7 | def test_very_active_minutes(): 8 | zf = create_zip() 9 | db = sqlite_utils.Database(memory=True) 10 | very_active_minutes = [ 11 | f.filename for f in zf.filelist if "very_active" in f.filename 12 | ] 13 | save_very_active_minutes(db, zf, very_active_minutes) 14 | very_active_minutes = list(sorted(db["very_active_minutes"].rows, key=lambda r: r["date"])) 15 | assert [ 16 | { 17 | "date": "2018-01-01", 18 | "value": 33 19 | }, 20 | { 21 | "date": "2018-01-02", 22 | "value": 59 23 | }, 24 | { 25 | "date": "2018-01-03", 26 | "value": 42 27 | } 28 | ] == very_active_minutes 29 | -------------------------------------------------------------------------------- /tests/test_resting_heart_rates.py: -------------------------------------------------------------------------------- 1 | from fitbit_to_sqlite.utils import save_resting_heart_rates 2 | import pathlib 3 | import sqlite_utils 4 | from .utils import create_zip 5 | 6 | 7 | def test_resting_heart_rate(): 8 | zf = create_zip() 9 | db = sqlite_utils.Database(memory=True) 10 | heart_rates = [ 11 | f.filename for f in zf.filelist if "resting_heart_rate" in f.filename 12 | ] 13 | save_resting_heart_rates(db, zf, heart_rates) 14 | heart_rates = list(sorted(db["resting_heart_rate"].rows, key=lambda r: r["date"])) 15 | assert [ 16 | { 17 | "date": "2018-12-30", 18 | "value": 59.420772552490234, 19 | "error": 6.787134170532227 20 | }, 21 | { 22 | "date": "2018-12-31", 23 | "value": 58.29636573791504, 24 | "error": 6.787102699279785 25 | }, 26 | ] == heart_rates 27 | -------------------------------------------------------------------------------- /tests/test_lightly_active_minutes.py: -------------------------------------------------------------------------------- 1 | from fitbit_to_sqlite.utils import save_lightly_active_minutes 2 | import pathlib 3 | import sqlite_utils 4 | from .utils import create_zip 5 | 6 | 7 | def test_lightly_active_minutes(): 8 | zf = create_zip() 9 | db = sqlite_utils.Database(memory=True) 10 | lightly_active_minutes = [ 11 | f.filename for f in zf.filelist if "lightly_active" in f.filename 12 | ] 13 | save_lightly_active_minutes(db, zf, lightly_active_minutes) 14 | lightly_active_minutes = list(sorted(db["lightly_active_minutes"].rows, key=lambda r: r["date"])) 15 | assert [ 16 | { 17 | "date": "2018-01-01", 18 | "value": 266 19 | }, 20 | { 21 | "date": "2018-01-02", 22 | "value": 165 23 | }, 24 | { 25 | "date": "2018-01-03", 26 | "value": 160 27 | } 28 | ] == lightly_active_minutes 29 | -------------------------------------------------------------------------------- /tests/test_moderately_active_minutes.py: -------------------------------------------------------------------------------- 1 | from fitbit_to_sqlite.utils import save_moderately_active_minutes 2 | import pathlib 3 | import sqlite_utils 4 | from .utils import create_zip 5 | 6 | 7 | def test_moderately_active_minutes(): 8 | zf = create_zip() 9 | db = sqlite_utils.Database(memory=True) 10 | moderately_active_minutes = [ 11 | f.filename for f in zf.filelist if "moderately_active" in f.filename 12 | ] 13 | save_moderately_active_minutes(db, zf, moderately_active_minutes) 14 | moderately_active_minutes = list(sorted(db["moderately_active_minutes"].rows, key=lambda r: r["date"])) 15 | assert [ 16 | { 17 | "date": "2018-01-01", 18 | "value": 22 19 | }, 20 | { 21 | "date": "2018-01-02", 22 | "value": 17 23 | }, 24 | { 25 | "date": "2018-01-03", 26 | "value": 13 27 | } 28 | ] == moderately_active_minutes 29 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | import os 3 | 4 | VERSION = "0.6" 5 | 6 | 7 | def get_long_description(): 8 | with open( 9 | os.path.join(os.path.dirname(os.path.abspath(__file__)), "README.md"), 10 | encoding="utf8", 11 | ) as fp: 12 | return fp.read() 13 | 14 | 15 | setup( 16 | name="fitbit-to-sqlite", 17 | description="Save data from Fitbit Takeout to an SQLite database", 18 | long_description=get_long_description(), 19 | long_description_content_type="text/markdown", 20 | author="Phil Rossiter", 21 | url="https://github.com/mrphil007/fitbit-to-sqlite", 22 | license="Apache License, Version 2.0", 23 | version=VERSION, 24 | packages=["fitbit_to_sqlite"], 25 | entry_points=""" 26 | [console_scripts] 27 | fitbit-to-sqlite=fitbit_to_sqlite.cli:cli 28 | """, 29 | install_requires=["sqlite-utils>=2.7.2", "click"], 30 | extras_require={"test": ["pytest"]}, 31 | tests_require=["fitbit-to-sqlite[test]"], 32 | ) 33 | -------------------------------------------------------------------------------- /tests/test_heart_rate_zones.py: -------------------------------------------------------------------------------- 1 | from fitbit_to_sqlite.utils import save_heart_rate_zones 2 | import pathlib 3 | import sqlite_utils 4 | from .utils import create_zip 5 | 6 | 7 | def test_heart_rate_zones(): 8 | zf = create_zip() 9 | db = sqlite_utils.Database(memory=True) 10 | heart_rate_zones = [ 11 | f.filename for f in zf.filelist if "heart_rate_zones" in f.filename 12 | ] 13 | save_heart_rate_zones(db, zf, heart_rate_zones) 14 | heart_rate_zones = list( 15 | sorted(db["heart_rate_zones"].rows, key=lambda r: r["date"]) 16 | ) 17 | assert [ 18 | { 19 | "date": "2018-01-02", 20 | "below_zone_1": 1037, 21 | "in_zone_1": 154, 22 | "in_zone_2": 20, 23 | "in_zone_3": 10, 24 | }, 25 | { 26 | "date": "2018-04-11", 27 | "below_zone_1": 1239, 28 | "in_zone_1": 115, 29 | "in_zone_2": 0, 30 | "in_zone_3": 0, 31 | }, 32 | ] == heart_rate_zones 33 | -------------------------------------------------------------------------------- /tests/test_distances.py: -------------------------------------------------------------------------------- 1 | from fitbit_to_sqlite.utils import save_distances 2 | import pathlib 3 | import sqlite_utils 4 | from .utils import create_zip 5 | 6 | 7 | def test_distances(): 8 | zf = create_zip() 9 | db = sqlite_utils.Database(memory=True) 10 | distances = [ 11 | f.filename for f in zf.filelist if "distance" in f.filename 12 | ] 13 | save_distances(db, zf, distances) 14 | distances = list(sorted(db["distance"].rows, key=lambda r: r["dateTime"])) 15 | assert [ 16 | { 17 | "dateTime": "2017-12-31T16:42:00", 18 | "value": 4110 19 | }, 20 | { 21 | "dateTime": "2017-12-31T16:43:00", 22 | "value": 4340 23 | }, 24 | { 25 | "dateTime": "2017-12-31T16:44:00", 26 | "value": 3490 27 | }, 28 | { 29 | "dateTime": "2017-12-31T16:45:00", 30 | "value": 850 31 | }, 32 | { 33 | "dateTime": "2017-12-31T16:46:00", 34 | "value": 0 35 | } 36 | ] == distances 37 | -------------------------------------------------------------------------------- /tests/test_sleep_scores.py: -------------------------------------------------------------------------------- 1 | from fitbit_to_sqlite.utils import save_sleep_scores 2 | import pathlib 3 | import sqlite_utils 4 | from .utils import create_zip 5 | 6 | 7 | def test_sleep_scores(): 8 | zf = create_zip() 9 | db = sqlite_utils.Database(memory=True) 10 | sleep_scores = [ 11 | f.filename for f in zf.filelist if "sleep_score.csv" in f.filename 12 | ] 13 | save_sleep_scores(db, zf, sleep_scores) 14 | sleep_scores = list(sorted(db["sleep_scores"].rows, key=lambda r: r["sleep_date"])) 15 | assert [ 16 | { 17 | "sleep_date": "2019-08-22", 18 | "overall_score": 82, 19 | "composition_score": 21, 20 | "revitalization_score": 22, 21 | "duration_score": 39, 22 | "deep_sleep_minutes": 71, 23 | "resting_heart_rate": 56, 24 | "restlessness": 0.082497213 25 | }, 26 | { 27 | "sleep_date": "2019-08-29", 28 | "overall_score": 75, 29 | "composition_score": 18, 30 | "revitalization_score": 20, 31 | "duration_score": 37, 32 | "deep_sleep_minutes": 77, 33 | "resting_heart_rate": 59, 34 | "restlessness": 0.070093458 35 | }, 36 | ] == sleep_scores 37 | -------------------------------------------------------------------------------- /tests/test_sleep.py: -------------------------------------------------------------------------------- 1 | from fitbit_to_sqlite.utils import save_sleep 2 | import pathlib 3 | import sqlite_utils 4 | from .utils import create_zip 5 | 6 | 7 | def test_sleep(): 8 | zf = create_zip() 9 | db = sqlite_utils.Database(memory=True) 10 | sleep = [ 11 | f.filename for f in zf.filelist if "sleep.json" in f.filename 12 | ] 13 | save_sleep(db, zf, sleep) 14 | sleep = list(sorted(db["sleep"].rows, key=lambda r: r["sleep_date"])) 15 | assert [ 16 | { 17 | "sleep_date": "2018-02-02", 18 | "start_time": "2018-02-01T22:36:00", 19 | "end_time": "2018-02-02T06:42:00", 20 | "minutes_asleep": 452, 21 | "minutes_awake": 34, 22 | "minutes_to_fall_asleep": 0, 23 | "minutes_after_wakeup": 15, 24 | "time_in_bed": 486, 25 | "efficiency": 68, 26 | "type": "stages", 27 | "wake_minutes": 34, 28 | "light_minutes": 209, 29 | "deep_minutes": 137, 30 | "rem_minutes": 106, 31 | }, 32 | { 33 | "sleep_date": "2018-02-03", 34 | "start_time": "2018-02-02T22:27:30", 35 | "end_time": "2018-02-03T06:57:30", 36 | "minutes_asleep": 312, 37 | "minutes_awake": 198, 38 | "minutes_to_fall_asleep": 0, 39 | "minutes_after_wakeup": 0, 40 | "time_in_bed": 510, 41 | "efficiency": 61, 42 | "type": "classic", 43 | "wake_minutes": None, 44 | "light_minutes": None, 45 | "deep_minutes": None, 46 | "rem_minutes": None, 47 | }, 48 | ] == sleep 49 | -------------------------------------------------------------------------------- /tests/zip_contents/sleep.json: -------------------------------------------------------------------------------- 1 | [{ 2 | "logId" : 17386918523, 3 | "dateOfSleep" : "2018-02-02", 4 | "startTime" : "2018-02-01T22:36:00.000", 5 | "endTime" : "2018-02-02T06:42:00.000", 6 | "duration" : 29160000, 7 | "minutesToFallAsleep" : 0, 8 | "minutesAsleep" : 452, 9 | "minutesAwake" : 34, 10 | "minutesAfterWakeup" : 15, 11 | "timeInBed" : 486, 12 | "efficiency" : 68, 13 | "type" : "stages", 14 | "infoCode" : 0, 15 | "levels" : { 16 | "summary" : { 17 | "deep" : { 18 | "count" : 6, 19 | "minutes" : 137, 20 | "thirtyDayAvgMinutes" : 96 21 | }, 22 | "wake" : { 23 | "count" : 28, 24 | "minutes" : 34, 25 | "thirtyDayAvgMinutes" : 54 26 | }, 27 | "light" : { 28 | "count" : 25, 29 | "minutes" : 209, 30 | "thirtyDayAvgMinutes" : 244 31 | }, 32 | "rem" : { 33 | "count" : 9, 34 | "minutes" : 106, 35 | "thirtyDayAvgMinutes" : 102 36 | } 37 | } 38 | }, 39 | "mainSleep" : true 40 | },{ 41 | "logId" : 17243952890, 42 | "dateOfSleep" : "2018-02-03", 43 | "startTime" : "2018-02-02T22:27:30.000", 44 | "endTime" : "2018-02-03T06:57:30.000", 45 | "duration" : 30600000, 46 | "minutesToFallAsleep" : 0, 47 | "minutesAsleep" : 312, 48 | "minutesAwake" : 198, 49 | "minutesAfterWakeup" : 0, 50 | "timeInBed" : 510, 51 | "efficiency" : 61, 52 | "type" : "classic", 53 | "infoCode" : 3, 54 | "levels" : { 55 | "summary" : { 56 | "restless" : { 57 | "count" : 18, 58 | "minutes" : 195 59 | }, 60 | "awake" : { 61 | "count" : 1, 62 | "minutes" : 3 63 | }, 64 | "asleep" : { 65 | "count" : 0, 66 | "minutes" : 312 67 | } 68 | } 69 | }, 70 | "mainSleep" : true 71 | }] -------------------------------------------------------------------------------- /tests/test_exercise.py: -------------------------------------------------------------------------------- 1 | from fitbit_to_sqlite.utils import save_exercise 2 | import pathlib 3 | import sqlite_utils 4 | from .utils import create_zip 5 | 6 | 7 | def test_exercise(): 8 | zf = create_zip() 9 | db = sqlite_utils.Database(memory=True) 10 | exercise = [ 11 | f.filename for f in zf.filelist if "exercise" in f.filename 12 | ] 13 | save_exercise(db, zf, exercise) 14 | exercise = list(sorted(db["exercise"].rows, key=lambda r: r["start_time"])) 15 | assert [ 16 | { 17 | "date": "2018-01-01", 18 | "start_time": "2018-01-01T14:25:33", 19 | "activity_type": "Walk", 20 | "log_type": "auto_detected", 21 | "duration": 1229000, 22 | "average_heart_rate": 114, 23 | "steps": 1838, 24 | "sedentary_minutes": 0, 25 | "lightly_active_minutes": 1, 26 | "fairly_active_minutes": 2, 27 | "very_active_minutes": 18, 28 | "out_of_zones_minutes": 0, 29 | "fat_burn_minutes": 17, 30 | "cardio_minutes": 1, 31 | "peak_minutes": 0, 32 | "distance": None 33 | }, 34 | { 35 | "date": "2018-01-02", 36 | "start_time": "2018-01-02T15:07:22", 37 | "activity_type": "Walk", 38 | "log_type": "auto_detected", 39 | "duration": 972000, 40 | "average_heart_rate": 108, 41 | "steps": 1376, 42 | "sedentary_minutes": 0, 43 | "lightly_active_minutes": 0, 44 | "fairly_active_minutes": 1, 45 | "very_active_minutes": 15, 46 | "out_of_zones_minutes": 1, 47 | "fat_burn_minutes": 14, 48 | "cardio_minutes": 1, 49 | "peak_minutes": 0, 50 | "distance": None 51 | }, 52 | { 53 | "date": "2018-01-03", 54 | "start_time": "2018-01-03T18:25:35", 55 | "activity_type": "Run", 56 | "log_type": "tracker", 57 | "duration": 1168000, 58 | "average_heart_rate": 139, 59 | "steps": 2927, 60 | "sedentary_minutes": 0, 61 | "lightly_active_minutes": 0, 62 | "fairly_active_minutes": 0, 63 | "very_active_minutes": 20, 64 | "out_of_zones_minutes": 0, 65 | "fat_burn_minutes": 0, 66 | "cardio_minutes": 20, 67 | "peak_minutes": 0, 68 | "distance": 2.087447 69 | }, 70 | ] == exercise 71 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # fitbit-to-sqlite 2 | 3 | [![PyPI](https://img.shields.io/pypi/v/fitbit-to-sqlite.svg)](https://pypi.org/project/fitbit-to-sqlite/) 4 | [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/mrphil007/fitbit-to-sqlite/blob/master/LICENSE) 5 | 6 | Save data from Fitbit Takeout to an SQLite database. 7 | 8 | ## How to install 9 | 10 | $ pip install fitbit-to-sqlite 11 | 12 | Request your Fitbit data from the `Export Your Account Archive` section on this page https://www.fitbit.com/settings/data/export - wait for the email and download the zip file. 13 | 14 | This tool only supports a subset of the available data sources. More will be added over time. 15 | 16 | ## Resting Heart Rate 17 | 18 | You can import data on your resting heart rate over time by using this command: 19 | 20 | $ fitbit-to-sqlite resting-heart-rate fitbit.db MyFitbitData.zip 21 | 22 | This will create a database file called `fitbit.db` if one does not already exist. 23 | 24 | ## Distance 25 | 26 | You can import data on the distance you have travelled each minute of each day by using the following command. Note that this also creates an analysis view called `distance_v` which converts the distances to km and miles. 27 | 28 | $ fitbit-to-sqlite distance fitbit.db MyFitbitData.zip 29 | 30 | ## Minutes Active 31 | 32 | You can import data on your activity minutes, which Fitbit classifies into `Sedentary`, `Lightly Active`, `Moderately Active` and `Very Active` using the following command. Note that this creates separate database tables for each, but they are also combined together into a view for analysis called `minutes_active_v`. 33 | 34 | $ fitbit-to-sqlite minutes-active fitbit.db MyFitbitData.zip 35 | 36 | ## Exercise 37 | 38 | You can import data on your exercise activities using the following command. Note that this imports a subset of all fields. 39 | 40 | $ fitbit-to-sqlite exercise fitbit.db MyFitbitData.zip 41 | 42 | ## Sleep 43 | 44 | You can import sleep log data using the following command. Note that some fields are only populated for sleep captured in `stages`. A second table called `sleep_scores` is also created which includes the scores (out of 100) which Fitbit have started generating. 45 | 46 | $ fitbit-to-sqlite sleep fitbit.db MyFitbitData.zip 47 | 48 | ## Heart Rate Zones 49 | 50 | You can import data on the time you have spent across the four heart rate zones which Fitbit defines based on your maximum heart rate. In the app these are usually referred to as "Below Zones", "Fat Burn", "Cardio" and "Peak" but here they are imported as `below_zone_1`, `in_zone_1`, `in_zone_2` and `in_zone_3`. 51 | 52 | $ fitbit-to-sqlite heart-rate-zones fitbit.db MyFitbitData.zip 53 | 54 | ## Browsing your data with Datasette 55 | 56 | Once you have imported Fitbit data into an SQLite database file you can browse your data using [Datasette](https://github.com/simonw/datasette). Install Datasette like so: 57 | 58 | $ pip install datasette 59 | 60 | Now browse your data by running this and then visiting `http://localhost:8001/` 61 | 62 | $ datasette fitbit.db 63 | 64 | ## Thanks 65 | 66 | This package is heavily inspired by the interesting work on [Personal Analytics](https://simonwillison.net/2019/Oct/7/dogsheep/) which Simon 67 | Willison has been doing [here](https://dogsheep.github.io/). 68 | -------------------------------------------------------------------------------- /tests/zip_contents/exercise.json: -------------------------------------------------------------------------------- 1 | [{ 2 | "logId" : 32289523590, 3 | "activityName" : "Walk", 4 | "activityTypeId" : 90013, 5 | "activityLevel" : [{ 6 | "minutes" : 0, 7 | "name" : "sedentary" 8 | },{ 9 | "minutes" : 1, 10 | "name" : "lightly" 11 | },{ 12 | "minutes" : 2, 13 | "name" : "fairly" 14 | },{ 15 | "minutes" : 18, 16 | "name" : "very" 17 | }], 18 | "averageHeartRate" : 114, 19 | "calories" : 180, 20 | "duration" : 1229000, 21 | "activeDuration" : 1229000, 22 | "steps" : 1838, 23 | "logType" : "auto_detected", 24 | "manualValuesSpecified" : { 25 | "calories" : false, 26 | "distance" : false, 27 | "steps" : false 28 | }, 29 | "heartRateZones" : [{ 30 | "name" : "Out of Range", 31 | "min" : 30, 32 | "max" : 89, 33 | "minutes" : 0 34 | },{ 35 | "name" : "Fat Burn", 36 | "min" : 89, 37 | "max" : 124, 38 | "minutes" : 17 39 | },{ 40 | "name" : "Cardio", 41 | "min" : 124, 42 | "max" : 151, 43 | "minutes" : 1 44 | },{ 45 | "name" : "Peak", 46 | "min" : 151, 47 | "max" : 220, 48 | "minutes" : 0 49 | }], 50 | "lastModified" : "01/01/18 15:28:34", 51 | "startTime" : "01/01/18 14:25:33", 52 | "originalStartTime" : "01/01/18 14:25:33", 53 | "originalDuration" : 1229000, 54 | "elevationGain" : 30.0, 55 | "hasGps" : false, 56 | "shouldFetchDetails" : false, 57 | "hasActiveZoneMinutes" : false 58 | },{ 59 | "logId" : 32289523598, 60 | "activityName" : "Walk", 61 | "activityTypeId" : 90013, 62 | "activityLevel" : [{ 63 | "minutes" : 0, 64 | "name" : "sedentary" 65 | },{ 66 | "minutes" : 0, 67 | "name" : "lightly" 68 | },{ 69 | "minutes" : 1, 70 | "name" : "fairly" 71 | },{ 72 | "minutes" : 15, 73 | "name" : "very" 74 | }], 75 | "averageHeartRate" : 108, 76 | "calories" : 133, 77 | "duration" : 972000, 78 | "activeDuration" : 972000, 79 | "steps" : 1376, 80 | "logType" : "auto_detected", 81 | "manualValuesSpecified" : { 82 | "calories" : false, 83 | "distance" : false, 84 | "steps" : false 85 | }, 86 | "heartRateZones" : [{ 87 | "name" : "Out of Range", 88 | "min" : 30, 89 | "max" : 89, 90 | "minutes" : 1 91 | },{ 92 | "name" : "Fat Burn", 93 | "min" : 89, 94 | "max" : 124, 95 | "minutes" : 14 96 | },{ 97 | "name" : "Cardio", 98 | "min" : 124, 99 | "max" : 151, 100 | "minutes" : 1 101 | },{ 102 | "name" : "Peak", 103 | "min" : 151, 104 | "max" : 220, 105 | "minutes" : 0 106 | }], 107 | "lastModified" : "01/02/18 15:28:34", 108 | "startTime" : "01/02/18 15:07:22", 109 | "originalStartTime" : "01/02/18 15:07:22", 110 | "originalDuration" : 972000, 111 | "elevationGain" : 30.0, 112 | "hasGps" : false, 113 | "shouldFetchDetails" : false, 114 | "hasActiveZoneMinutes" : false 115 | },{ 116 | "logId" : 33445279392, 117 | "activityName" : "Run", 118 | "activityTypeId" : 90009, 119 | "activityLevel" : [{ 120 | "minutes" : 0, 121 | "name" : "sedentary" 122 | },{ 123 | "minutes" : 0, 124 | "name" : "lightly" 125 | },{ 126 | "minutes" : 0, 127 | "name" : "fairly" 128 | },{ 129 | "minutes" : 20, 130 | "name" : "very" 131 | }], 132 | "averageHeartRate" : 139, 133 | "calories" : 243, 134 | "distance" : 2.087447, 135 | "distanceUnit" : "Mile", 136 | "duration" : 1168000, 137 | "activeDuration" : 1168000, 138 | "steps" : 2927, 139 | "source" : { 140 | "type" : "tracker", 141 | "name" : "Charge 2", 142 | "id" : "113012987", 143 | "url" : "https://www.fitbit.com/", 144 | "trackerFeatures" : ["CALORIES","STEPS","ELEVATION","GPS","VO2_MAX","HEARTRATE","DISTANCE","PACE"] 145 | }, 146 | "logType" : "tracker", 147 | "manualValuesSpecified" : { 148 | "calories" : false, 149 | "distance" : false, 150 | "steps" : false 151 | }, 152 | "heartRateZones" : [{ 153 | "name" : "Out of Range", 154 | "min" : 30, 155 | "max" : 89, 156 | "minutes" : 0 157 | },{ 158 | "name" : "Fat Burn", 159 | "min" : 89, 160 | "max" : 124, 161 | "minutes" : 0 162 | },{ 163 | "name" : "Cardio", 164 | "min" : 124, 165 | "max" : 151, 166 | "minutes" : 20 167 | },{ 168 | "name" : "Peak", 169 | "min" : 151, 170 | "max" : 220, 171 | "minutes" : 0 172 | }], 173 | "speed" : 6.4339119863013705, 174 | "pace" : 559.5351642460862, 175 | "lastModified" : "01/03/18 18:48:08", 176 | "startTime" : "01/03/18 18:25:35", 177 | "originalStartTime" : "01/03/20 18:25:35", 178 | "originalDuration" : 1168000, 179 | "elevationGain" : 17.998688, 180 | "hasGps" : false, 181 | "shouldFetchDetails" : false, 182 | "hasActiveZoneMinutes" : false 183 | }] -------------------------------------------------------------------------------- /fitbit_to_sqlite/cli.py: -------------------------------------------------------------------------------- 1 | import click 2 | import json 3 | import zipfile 4 | import sqlite_utils 5 | from . import utils 6 | 7 | 8 | @click.group() 9 | @click.version_option() 10 | def cli(): 11 | "Save Fitbit data to a SQLite database" 12 | 13 | 14 | @cli.command(name="resting-heart-rate") 15 | @click.argument( 16 | "db_path", 17 | type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), 18 | required=True, 19 | ) 20 | @click.argument( 21 | "zip_path", 22 | type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), 23 | required=True, 24 | ) 25 | def resting_heart_rate(db_path, zip_path): 26 | "Save resting heart rate data from Takeout zip to SQLite" 27 | db = sqlite_utils.Database(db_path) 28 | zf = zipfile.ZipFile(zip_path) 29 | # Find all the relevant resting heart rate files 30 | heart_rates = [ 31 | f.filename for f in zf.filelist if "resting_heart_rate" in f.filename 32 | ] 33 | with click.progressbar(heart_rates, label="Loading resting heart rate data") as bar: 34 | utils.save_resting_heart_rates(db, zf, bar) 35 | 36 | 37 | @cli.command(name="distance") 38 | @click.argument( 39 | "db_path", 40 | type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), 41 | required=True, 42 | ) 43 | @click.argument( 44 | "zip_path", 45 | type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), 46 | required=True, 47 | ) 48 | def distance(db_path, zip_path): 49 | "Save Distance data from Takeout zip to SQLite" 50 | db = sqlite_utils.Database(db_path) 51 | zf = zipfile.ZipFile(zip_path) 52 | # Find all the relevant distance files 53 | distances = [f.filename for f in zf.filelist if "distance" in f.filename] 54 | with click.progressbar(distances, label="Loading distance data") as bar: 55 | utils.save_distances(db, zf, bar) 56 | # Add view on distance data 57 | utils.create_views(db) 58 | 59 | 60 | @cli.command(name="minutes-active") 61 | @click.argument( 62 | "db_path", 63 | type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), 64 | required=True, 65 | ) 66 | @click.argument( 67 | "zip_path", 68 | type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), 69 | required=True, 70 | ) 71 | def minutes_active(db_path, zip_path): 72 | "Save data on minutes active from Takeout zip to SQLite" 73 | db = sqlite_utils.Database(db_path) 74 | zf = zipfile.ZipFile(zip_path) 75 | # Find relevant sedentary minutes files 76 | sedentary_minutes = [f.filename for f in zf.filelist if "sedentary" in f.filename] 77 | with click.progressbar( 78 | sedentary_minutes, label="Loading sedentary minutes data" 79 | ) as bar: 80 | utils.save_sedentary_minutes(db, zf, bar) 81 | # Find relevant lightly active minutes files 82 | lightly_active_minutes = [ 83 | f.filename for f in zf.filelist if "lightly_active" in f.filename 84 | ] 85 | with click.progressbar( 86 | lightly_active_minutes, label="Loading lightly active minutes data" 87 | ) as bar: 88 | utils.save_lightly_active_minutes(db, zf, bar) 89 | # Find relevant moderately active minutes files 90 | moderately_active_minutes = [ 91 | f.filename for f in zf.filelist if "moderately_active" in f.filename 92 | ] 93 | with click.progressbar( 94 | moderately_active_minutes, label="Loading moderately active minutes data" 95 | ) as bar: 96 | utils.save_moderately_active_minutes(db, zf, bar) 97 | # Find relevant very active minutes files 98 | very_active_minutes = [ 99 | f.filename for f in zf.filelist if "very_active" in f.filename 100 | ] 101 | with click.progressbar( 102 | very_active_minutes, label="Loading very active minutes data" 103 | ) as bar: 104 | utils.save_very_active_minutes(db, zf, bar) 105 | # Create analysis view 106 | utils.create_views(db) 107 | 108 | 109 | @cli.command(name="exercise") 110 | @click.argument( 111 | "db_path", 112 | type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), 113 | required=True, 114 | ) 115 | @click.argument( 116 | "zip_path", 117 | type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), 118 | required=True, 119 | ) 120 | def exercise(db_path, zip_path): 121 | "Save data on Exercise activities from Takeout zip to SQLite" 122 | db = sqlite_utils.Database(db_path) 123 | zf = zipfile.ZipFile(zip_path) 124 | # Find relevant exercise files 125 | exercise = [f.filename for f in zf.filelist if "exercise" in f.filename] 126 | with click.progressbar(exercise, label="Loading exercise data") as bar: 127 | utils.save_exercise(db, zf, bar) 128 | 129 | 130 | @cli.command(name="sleep") 131 | @click.argument( 132 | "db_path", 133 | type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), 134 | required=True, 135 | ) 136 | @click.argument( 137 | "zip_path", 138 | type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), 139 | required=True, 140 | ) 141 | def sleep(db_path, zip_path): 142 | "Save data on Sleep from Takeout zip to SQLite" 143 | db = sqlite_utils.Database(db_path) 144 | zf = zipfile.ZipFile(zip_path) 145 | # Find relevant sleep files 146 | sleep = [f.filename for f in zf.filelist if "sleep-" in f.filename] 147 | with click.progressbar(sleep, label="Loading sleep data") as bar: 148 | utils.save_sleep(db, zf, bar) 149 | # Also save the sleep scores which are in a separate CSV 150 | sleep_scores = [f.filename for f in zf.filelist if "sleep_score.csv" in f.filename] 151 | utils.save_sleep_scores(db, zf, sleep_scores) 152 | 153 | 154 | @cli.command(name="heart-rate-zones") 155 | @click.argument( 156 | "db_path", 157 | type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), 158 | required=True, 159 | ) 160 | @click.argument( 161 | "zip_path", 162 | type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), 163 | required=True, 164 | ) 165 | def heart_rate_zones(db_path, zip_path): 166 | "Save data on Time in Heart Rate Zones from Takeout zip to SQLite" 167 | db = sqlite_utils.Database(db_path) 168 | zf = zipfile.ZipFile(zip_path) 169 | # Find relevant heart rate zones files 170 | heart_rate_zones = [ 171 | f.filename for f in zf.filelist if "heart_rate_zones" in f.filename 172 | ] 173 | with click.progressbar( 174 | heart_rate_zones, label="Loading heart rate zones data" 175 | ) as bar: 176 | utils.save_heart_rate_zones(db, zf, bar) 177 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /fitbit_to_sqlite/utils.py: -------------------------------------------------------------------------------- 1 | import json 2 | import csv 3 | from io import TextIOWrapper 4 | import datetime 5 | import sqlite_utils 6 | 7 | 8 | def save_resting_heart_rates(db, zf, heart_rates): 9 | for filename in heart_rates: 10 | heart_rate = json.load(zf.open(filename)) 11 | db["resting_heart_rate"].upsert_all( 12 | ( 13 | { 14 | "date": datetime.datetime.strptime( 15 | row["dateTime"], "%m/%d/%y %H:%M:%S" 16 | ).date(), 17 | "value": row["value"]["value"], 18 | "error": row["value"]["error"], 19 | } 20 | for row in heart_rate 21 | ), 22 | pk="date", 23 | ) 24 | 25 | 26 | def save_distances(db, zf, distances): 27 | for filename in distances: 28 | distance = json.load(zf.open(filename)) 29 | db["distance"].upsert_all( 30 | ( 31 | { 32 | "dateTime": datetime.datetime.strptime( 33 | row["dateTime"], "%m/%d/%y %H:%M:%S" 34 | ), 35 | "value": row["value"], 36 | } 37 | for row in distance 38 | ), 39 | pk="dateTime", 40 | columns={"dateTime": str, "value": int}, 41 | ) 42 | 43 | 44 | def save_sedentary_minutes(db, zf, sedentary_minutes): 45 | for filename in sedentary_minutes: 46 | sedentary_minutes = json.load(zf.open(filename)) 47 | db["sedentary_minutes"].upsert_all( 48 | ( 49 | { 50 | "date": datetime.datetime.strptime( 51 | row["dateTime"], "%m/%d/%y %H:%M:%S" 52 | ).date(), 53 | "value": row["value"], 54 | } 55 | for row in sedentary_minutes 56 | ), 57 | pk="date", 58 | columns={"date": str, "value": int}, 59 | ) 60 | 61 | 62 | def save_lightly_active_minutes(db, zf, lightly_active_minutes): 63 | for filename in lightly_active_minutes: 64 | lightly_active_minutes = json.load(zf.open(filename)) 65 | db["lightly_active_minutes"].upsert_all( 66 | ( 67 | { 68 | "date": datetime.datetime.strptime( 69 | row["dateTime"], "%m/%d/%y %H:%M:%S" 70 | ).date(), 71 | "value": row["value"], 72 | } 73 | for row in lightly_active_minutes 74 | ), 75 | pk="date", 76 | columns={"date": str, "value": int}, 77 | ) 78 | 79 | 80 | def save_moderately_active_minutes(db, zf, moderately_active_minutes): 81 | for filename in moderately_active_minutes: 82 | moderately_active_minutes = json.load(zf.open(filename)) 83 | db["moderately_active_minutes"].upsert_all( 84 | ( 85 | { 86 | "date": datetime.datetime.strptime( 87 | row["dateTime"], "%m/%d/%y %H:%M:%S" 88 | ).date(), 89 | "value": row["value"], 90 | } 91 | for row in moderately_active_minutes 92 | ), 93 | pk="date", 94 | columns={"date": str, "value": int}, 95 | ) 96 | 97 | 98 | def save_very_active_minutes(db, zf, very_active_minutes): 99 | for filename in very_active_minutes: 100 | very_active_minutes = json.load(zf.open(filename)) 101 | db["very_active_minutes"].upsert_all( 102 | ( 103 | { 104 | "date": datetime.datetime.strptime( 105 | row["dateTime"], "%m/%d/%y %H:%M:%S" 106 | ).date(), 107 | "value": row["value"], 108 | } 109 | for row in very_active_minutes 110 | ), 111 | pk="date", 112 | columns={"date": str, "value": int}, 113 | ) 114 | 115 | 116 | def save_exercise(db, zf, exercise): 117 | for filename in exercise: 118 | exercise = json.load(zf.open(filename)) 119 | db["exercise"].upsert_all( 120 | ( 121 | { 122 | "date": datetime.datetime.strptime( 123 | row["startTime"], "%m/%d/%y %H:%M:%S" 124 | ).date(), 125 | "start_time": datetime.datetime.strptime( 126 | row["startTime"], "%m/%d/%y %H:%M:%S" 127 | ), 128 | "activity_type": row["activityName"], 129 | "log_type": row["logType"], 130 | "duration": row["activeDuration"], 131 | "average_heart_rate": row["averageHeartRate"] 132 | if "averageHeartRate" in row 133 | else None, 134 | "steps": row["steps"] if "steps" in row else None, 135 | "sedentary_minutes": row["activityLevel"][0]["minutes"], 136 | "lightly_active_minutes": row["activityLevel"][1]["minutes"], 137 | "fairly_active_minutes": row["activityLevel"][2]["minutes"], 138 | "very_active_minutes": row["activityLevel"][3]["minutes"], 139 | "out_of_zones_minutes": row["heartRateZones"][0]["minutes"] 140 | if "heartRateZones" in row 141 | else None, 142 | "fat_burn_minutes": row["heartRateZones"][1]["minutes"] 143 | if "heartRateZones" in row 144 | else None, 145 | "cardio_minutes": row["heartRateZones"][2]["minutes"] 146 | if "heartRateZones" in row 147 | else None, 148 | "peak_minutes": row["heartRateZones"][3]["minutes"] 149 | if "heartRateZones" in row 150 | else None, 151 | "distance": row["distance"] if "distance" in row else None, 152 | } 153 | for row in exercise 154 | ), 155 | pk="start_time", 156 | ) 157 | 158 | 159 | def save_sleep(db, zf, sleep): 160 | for filename in sleep: 161 | sleep = json.load(zf.open(filename)) 162 | db["sleep"].upsert_all( 163 | ( 164 | { 165 | "sleep_date": datetime.datetime.strptime( 166 | row["dateOfSleep"], "%Y-%m-%d" 167 | ).date(), 168 | "start_time": datetime.datetime.strptime( 169 | row["startTime"], "%Y-%m-%dT%H:%M:%S.%f" 170 | ), 171 | "end_time": datetime.datetime.strptime( 172 | row["endTime"], "%Y-%m-%dT%H:%M:%S.%f" 173 | ), 174 | "minutes_asleep": row["minutesAsleep"], 175 | "minutes_awake": row["minutesAwake"], 176 | "minutes_to_fall_asleep": row["minutesToFallAsleep"], 177 | "minutes_after_wakeup": row["minutesAfterWakeup"], 178 | "time_in_bed": row["timeInBed"], 179 | "efficiency": row["efficiency"], 180 | "type": row["type"], 181 | "wake_minutes": row["levels"]["summary"]["wake"]["minutes"] 182 | if row["type"] == "stages" 183 | else None, 184 | "light_minutes": row["levels"]["summary"]["light"]["minutes"] 185 | if row["type"] == "stages" 186 | else None, 187 | "deep_minutes": row["levels"]["summary"]["deep"]["minutes"] 188 | if row["type"] == "stages" 189 | else None, 190 | "rem_minutes": row["levels"]["summary"]["rem"]["minutes"] 191 | if row["type"] == "stages" 192 | else None, 193 | } 194 | for row in sleep 195 | ), 196 | pk="sleep_date", 197 | ) 198 | 199 | 200 | def save_sleep_scores(db, zf, sleep_scores): 201 | for filename in sleep_scores: 202 | sleep_scores = csv.DictReader(TextIOWrapper(zf.open(filename))) 203 | db["sleep_scores"].upsert_all( 204 | ( 205 | { 206 | "sleep_date": datetime.datetime.strptime( 207 | row["timestamp"], "%Y-%m-%dT%H:%M:%SZ" 208 | ).date(), 209 | "overall_score": row["overall_score"], 210 | "composition_score": row["composition_score"], 211 | "revitalization_score": row["revitalization_score"], 212 | "duration_score": row["duration_score"], 213 | "deep_sleep_minutes": row["deep_sleep_in_minutes"], 214 | "resting_heart_rate": row["resting_heart_rate"], 215 | "restlessness": row["restlessness"], 216 | } 217 | for row in sleep_scores 218 | ), 219 | pk="sleep_date", 220 | columns={ 221 | "sleep_date": str, 222 | "overall_score": int, 223 | "composition_score": int, 224 | "revitalization_score": int, 225 | "duration_score": int, 226 | "deep_sleep_minutes": int, 227 | "resting_heart_rate": int, 228 | "restlessness": float, 229 | }, 230 | ) 231 | 232 | 233 | def save_heart_rate_zones(db, zf, heart_rate_zones): 234 | for filename in heart_rate_zones: 235 | heart_rate_zones = json.load(zf.open(filename)) 236 | db["heart_rate_zones"].upsert_all( 237 | ( 238 | { 239 | "date": datetime.datetime.strptime( 240 | row["dateTime"], "%m/%d/%y %H:%M:%S" 241 | ).date(), 242 | "below_zone_1": row["value"]["valuesInZones"][ 243 | "BELOW_DEFAULT_ZONE_1" 244 | ], 245 | "in_zone_1": row["value"]["valuesInZones"]["IN_DEFAULT_ZONE_1"], 246 | "in_zone_2": row["value"]["valuesInZones"]["IN_DEFAULT_ZONE_2"], 247 | "in_zone_3": row["value"]["valuesInZones"]["IN_DEFAULT_ZONE_3"], 248 | } 249 | for row in heart_rate_zones 250 | ), 251 | pk="date", 252 | columns={ 253 | "date": str, 254 | "below_zone_1": int, 255 | "in_zone_1": int, 256 | "in_zone_2": int, 257 | "in_zone_3": int, 258 | }, 259 | ) 260 | 261 | 262 | def create_views(db): 263 | for name, sql in ( 264 | ( 265 | "distance_v", 266 | """ 267 | SELECT 268 | d.dateTime AS date_time, 269 | DATE(d.dateTime) AS date, 270 | -- Distance is in cm, convert to km 271 | CAST(d.value AS FLOAT)/100000 AS distance_km, 272 | -- Approximate conversation of km to m 273 | CAST(d.value AS FLOAT)/100000/1.609344 AS distance_miles 274 | FROM 275 | distance d 276 | """, 277 | ), 278 | ( 279 | "minutes_active_v", 280 | """ 281 | SELECT 282 | 'sendentary' AS minutes_type, 283 | d.* 284 | FROM 285 | sedentary_minutes d 286 | UNION ALL 287 | SELECT 288 | 'lightly_active' AS minutes_type, 289 | d.* 290 | FROM 291 | lightly_active_minutes d 292 | UNION ALL 293 | SELECT 294 | 'moderately_active' AS minutes_type, 295 | d.* 296 | FROM 297 | moderately_active_minutes d 298 | UNION ALL 299 | SELECT 300 | 'very_active' AS minutes_type, 301 | d.* 302 | FROM 303 | very_active_minutes d 304 | """, 305 | ), 306 | ): 307 | try: 308 | db.create_view(name, sql) 309 | except Exception: 310 | pass 311 | --------------------------------------------------------------------------------