Skip to content

Instantly share code, notes, and snippets.

@yzqzss
Created September 14, 2024 03:00
Show Gist options
  • Select an option

  • Save yzqzss/13b23b40a05df7bf634a716c73bdd639 to your computer and use it in GitHub Desktop.

Select an option

Save yzqzss/13b23b40a05df7bf634a716c73bdd639 to your computer and use it in GitHub Desktop.
小米运动 -> ics
import csv
import json
import zoneinfo
import icalendar
from datetime import datetime
with open("center_fitness_data.csv", "r") as csvf, open("sleep.ics", "w") as icsf:
calendar = icalendar.Calendar()
calendar.add("version", "2.0")
calendar.add("prodid", "-//MIFitness//Sleep//EN")
reader = csv.DictReader(csvf)
for row in reader:
# print(row)
if row["Key"] != "sleep":
continue
value = json.loads(row["Value"])
bedtime, wake_up_time = value["bedtime"], value["wake_up_time"]
# generate an icalendar journal
journal = icalendar.Event()
journal.add("summary", "Sleep")
journal.add("dtstart", datetime.fromtimestamp(bedtime, tz=zoneinfo.ZoneInfo("UTC")))
journal.add("dtend", datetime.fromtimestamp(wake_up_time, tz=zoneinfo.ZoneInfo("UTC")))
journal.add("dtstamp", datetime.fromtimestamp(wake_up_time, tz=zoneinfo.ZoneInfo("UTC")))
calendar.add_component(journal)
icsf.write(calendar.to_ical().decode("utf-8"))
import sqlite3
import json
import zoneinfo
import icalendar
from datetime import datetime
bedtimes = set()
with open("sleep.ics", "r") as icsf:
calendar = icalendar.Calendar.from_ical(icsf.read())
for component in calendar.walk():
component: icalendar.Event
if component.name == "VEVENT":
bedtimes.add(int(component.get("dtstart").dt.timestamp()))
print(bedtimes)
with sqlite3.connect("fitness_data") as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM sleep_segment")
for row in cursor.fetchall():
# print(row)
row = dict(zip([description[0] for description in cursor.description], row))
if row["key"] != "sleep" and row["isComplete"] != 1 and row["isUpload"] != 1:
print("Skipping row:", row)
continue
value = json.loads(row["value"])
bedtime, wake_up_time = value["bedtime"], value["wake_up_time"]
if int(bedtime) in bedtimes:
continue
print(bedtime, wake_up_time)
event = icalendar.Event()
event.add("summary", "Sleep")
event.add("dtstart", datetime.fromtimestamp(bedtime, tz=zoneinfo.ZoneInfo("UTC")))
event.add("dtend", datetime.fromtimestamp(wake_up_time, tz=zoneinfo.ZoneInfo("UTC")))
event.add("dtstamp", datetime.fromtimestamp(wake_up_time, tz=zoneinfo.ZoneInfo("UTC")))
calendar.add_component(event)
with open("sleep.ics", "w") as icsf:
icsf.write(calendar.to_ical().decode("utf-8"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment