Last Night's Sleep
COMMENT
Made by: mvan231
Originally created before advanced sleep tracking was available in WatchOS 9 / iOS 16. Updated in 2022 for the inclusion of these sleep stages
Updates for showing Hours and Minutes of total sleep time vs x.y hours
V4
- Updated calculation method to use seconds instead of relying on the sum method
- Handling added for when detailed sleep data isn't available
CALENDAR
Subtract
1
days
from
Current Date

Adjusted Date
DATE
Specified Date
Adjusted Date
18:00

Date
TEXT
{
"In Bed":[],
"Core":[],
"REM":[],
"Deep":[],
"Awake":[]
}

Text
VARIABLES
Set variable
Dict
to
Text
HEALTH
Find
All Health Samples
where
All the following are true [{'class': 'filter-property', 'value': 'Type'}, {'class': 'filter-operator', 'value': 'is'}, {'class': 'filter-benchmark', 'value': 'Sleep'}] [{'class': 'filter-property', 'value': 'Start Date'}, {'class': 'filter-operator', 'value': 'is in the last'}, {'class': 'filter-benchmark', 'value': '1', 'glyph': '', 'UUID': ''}, {'class': 'filter-unit', 'value': 'day', 'glyph': '', 'UUID': ''}]

Health Samples
SCRIPTING
Repeat with each item in
Health Samples

Repeat Results
NOTHING
Nothing
SCRIPTING
If
Date
is less than
Repeat Item
SCRIPTING
Get
Value
for
Repeat Item
in
Dict

Dictionary Value
CALENDAR
Get time between
Repeat Item
and
Repeat Item
in
Seconds

Time Between Dates
LIST

List
SCRIPTING
Set
Repeat Item
to
List
in
Dictionary

Dictionary
VARIABLES
Set variable
Dict
to
Dictionary
VARIABLES
Get
Repeat Item
SCRIPTING
End If

If Result
SCRIPTING
End Repeat

Repeat Results
SCRIPTING
Get
First Item
from
Repeat Results

Item from List
SCRIPTING
Get
Last Item
from
Repeat Results

Item from List
FILES
Filter
Dict

Files
SCRIPTING
Repeat with each item in
Files

Repeat Results
SCRIPTING
Get
Value
for
Repeat Item
in
Dict

Dictionary Value
MATHS
Calculate the
Sum
of
Dictionary Value

Statistics
SCRIPTING
If
Sum
is greater than
0
SCRIPTING
If
Repeat Item
is not
In Bed
SCRIPTING
If
Repeat Item
is not
Awake
VARIABLES
Add
Sum
to
Asleep
SCRIPTING
End If

If Result
SCRIPTING
End If

If Result
MISSING
calculateexpression Under Construction
MATHS
Round
Raw hours
to
Ones Place

Rounded Number
MISSING
calculateexpression Under Construction
MATHS
Round
Calculation Result
to
Ones Place

Rounded Number
TEXT
Rounded Minutes
for
Repeat Item
hours and
Rounded Hours
minutes

Text
SCRIPTING
End If

If Result
SCRIPTING
End Repeat

Repeat Results
MATHS
Calculate the
Sum
of
Asleep

Statistics
SCRIPTING
If
Sum
has any value
MISSING
calculateexpression Under Construction
MATHS
Round
RawH
to
Ones Place

Rounded Number
MISSING
calculateexpression Under Construction
MATHS
Round
Minutes
to
Ones Place

Rounded Number
TEXT
Rounded Minutes
hours
Rounded Hour
minutes

Text
SCRIPTING
Otherwise
TEXT
No detailed sleep data found

Text
SCRIPTING
End If

If Result
TEXT
Item from List
-
Repeat Results
Total Time Asleep:
If Result
Item from List

Text
DOCUMENTS
Show
Text
in Quick Look
Showcuts