Skip to content

Instantly share code, notes, and snippets.

@daylen

daylen/sleep_analysis.py

Last active Dec 26, 2019
Embed
What would you like to do?
#!/usr/bin/env python
# coding: utf-8
# In[27]:
import pandas as pd
import datetime
# In[2]:
df = pd.read_csv('~/Downloads/Health Metrics - Sleep.csv')
# In[78]:
# In[87]:
def find_latest_end():
date_to_end = {}
for idx, row in df.iterrows():
if row['Date'] in date_to_end:
existing = date_to_end[row['Date']]
cand = row['End']
if existing > cand:
# print('existing', existing, 'is larger than cand', cand)
continue
date_to_end[row['Date']] = row['End']
return {date: datetime.timedelta(hours=int(end[:2]), minutes=int(end[3:])) for (date, end) in date_to_end.items()}
def find_asleep():
date_to_asleep = {}
for idx, row in df.iterrows():
td = pd.to_timedelta(row['Asleep'] + ':00')
if row['Date'] in date_to_asleep:
date_to_asleep[row['Date']] += td
date_to_asleep[row['Date']] = td
return date_to_asleep
# In[88]:
date_to_end = find_latest_end()
# In[89]:
def filter_by_year(year, date_to_end):
return [end for (date, end) in date_to_end.items() if year in date]
# In[94]:
ends = filter_by_year('2019', date_to_end)
def avg_duration(ends):
seconds_past_midnight = sum(ends, datetime.timedelta(0)) / len(ends)
hours_past = seconds_past_midnight.seconds / 3600
print(int(hours_past), ':', int(60 * (hours_past - int(hours_past))))
avg_duration(ends)
# In[91]:
date_to_asleep = find_asleep()
# In[100]:
asleep = filter_by_year('2019', date_to_asleep)
avg_duration(asleep)
# In[ ]:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.