Skip to content

Instantly share code, notes, and snippets.

@k-sriram
Created October 20, 2021 14:07
Show Gist options
  • Save k-sriram/f90cdd0fd2fd0a0438dbe0ae08791ac8 to your computer and use it in GitHub Desktop.
Save k-sriram/f90cdd0fd2fd0a0438dbe0ae08791ac8 to your computer and use it in GitHub Desktop.
Sleep history plot
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import csv
import datetime
from dateutil import parser as dateparser
import numpy as np
from matplotlib import pyplot as plt
import os
import re
DAY = datetime.timedelta(days=1)
MIDNIGHT = datetime.time()
MINTIME = 0
MAXTIME = 24
def hours(time):
return time.hour + time.minute / 60
filere = re.compile(r"sleep_history_(\d{4}-\d{2}-\d{2}\.\d+)\.csv")
history_files = [f for f in os.listdir() if filere.match(f)]
history_files.sort()
csvfn = history_files[-1]
sleeptimes = list()
with open(csvfn) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
sleeptimes.append(
(dateparser.isoparse(row["bedtime"]), dateparser.isoparse(row["wake"]))
)
plotdates, plotlower, plotupper = list(), list(), list()
for s in sleeptimes:
lower = s[0]
while lower.date() < s[1].date():
plotdates.append(lower.date())
plotlower.append(hours(lower))
plotupper.append(MAXTIME)
lower = datetime.datetime.combine(
(DAY + lower).date(), MIDNIGHT, tzinfo=lower.tzinfo
)
else:
plotdates.append(lower.date())
plotlower.append(hours(lower))
plotupper.append(hours(s[1]))
plotdates, plotlower, plotupper = (
np.array(plotdates),
np.array(plotlower),
np.array(plotupper),
)
plotdatemin, plotdatemax = plotdates.min(), plotdates.max()
plotticks = [
plotdates.min() + datetime.timedelta(days=i)
for i in range((plotdates.max() - plotdates.min()).days)
if (plotdates.min() + datetime.timedelta(days=i)).weekday() == 6
]
plt.bar(plotdates, plotupper - plotlower, bottom=plotlower)
plt.ylim((0, 24))
plt.xticks(rotation=60, ticks=plotticks)
plt.yticks(ticks=(0, 6, 12, 18, 24))
plt.ylabel("Time")
plt.xlabel("Date (Sundays are axis labels)")
plt.tight_layout()
plt.savefig("sleepplot.png")
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment