This query is meant to serve as a proof-of-concept for parsing sleep data off of the fitbit API, which returns you a start date, and then a series of times. Given that these data are polled every minute, you can safely assume that, when you cross a date boundary, the next measurement of time will be "smaller" than the last, and we could just break it into two days.
However, in an extreme edge case where either the fitbit is reporting wrong, or
someone really is
sleeping for more than 24 hours,
we need to really break these data down a bit more consistently. This query
will do that, and then assign a proper date to the results so that it's a full
TIMESTAMP
instead of a simple TIME
reference.
The rd
value is used to calculate what the result should be, for comparison.
Running this should result in a dataset similar to the following:
postgres@[local]:5432/fitbit-dev =# \i example.sql
┌─────┬─────────────────────┬─────────────────────┐
│ idx │ intended_date │ calculated_date │
├─────┼─────────────────────┼─────────────────────┤
│ 1 │ 2016-06-21 11:52:00 │ 2016-06-21 11:52:00 │
│ 2 │ 2016-06-22 00:52:00 │ 2016-06-22 00:52:00 │
│ 3 │ 2016-06-22 10:52:00 │ 2016-06-22 10:52:00 │
│ 4 │ 2016-06-22 23:52:00 │ 2016-06-22 23:52:00 │
│ 5 │ 2016-06-23 00:52:00 │ 2016-06-23 00:52:00 │
└─────┴─────────────────────┴─────────────────────┘
(5 rows)