Created
July 8, 2023 05:39
-
-
Save Parsiuk/5ffa9aef62db5730402e64742a98de08 to your computer and use it in GitHub Desktop.
Import weight info from FirBit data export into MariaDB/MySQL database.
This file contains hidden or 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
import json | |
import os | |
import pymysql | |
from datetime import datetime | |
def pounds_to_kilograms(weight_in_pounds): | |
return weight_in_pounds * 0.45359237 | |
def convert_date(date_str): | |
date_obj = datetime.strptime(date_str, "%m/%d/%y") | |
return date_obj.strftime("%Y-%m-%d") | |
try: | |
connection = pymysql.connect( | |
host="hostname", | |
user="dbusername", | |
password="dbpassword", | |
database="databasename" | |
) | |
cursor = connection.cursor() | |
for filename in os.listdir('.'): | |
if filename.startswith('weight-') and filename.endswith('.json'): | |
with open(filename) as file: | |
data = json.load(file) | |
for entry in data: | |
log_id = entry['logId'] | |
weight = entry['weight'] | |
date = entry['date'] | |
weight_kg = pounds_to_kilograms(weight) | |
iso_date = convert_date(date) | |
query = "INSERT INTO weight_data (log_id, date, weight_kg) VALUES (%s, %s, %s)" | |
values = (log_id, iso_date, weight_kg) | |
try: | |
cursor.execute(query, values) | |
except pymysql.IntegrityError as e: | |
if e.args[0] == 1062: | |
print(f"Skipping duplicate record with log_id: {log_id}") | |
else: | |
raise e | |
connection.commit() | |
print("Data inserted successfully!") | |
except pymysql.Error as e: | |
print(f"Error connecting to MariaDB: {e}") | |
finally: | |
if connection: | |
cursor.close() | |
connection.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment