Hello @repchur,
Glad to hear that my old post helped you, too.
Basically, we had to apply one of two formulas to compute variable right_hours_slept:
(wake_time-bed_time)/3600 if bed_time is "at or after midnight." In this case both times belong to the same date and wake_time>bed_time. Therefore, dividing the (positive) difference of the SAS time values (i.e., numbers of seconds after midnight of that same date) by 3600 gives us the time difference in hours rather than seconds.
24+(wake_time-bed_time)/3600 if bed_time is "before midnight." In this case we assume that bed_time and wake_time belong to two consecutive days and that bed_time>wake_time. Therefore, variable right_hours_slept can be computed as the sum of the time (in hours) from bed_time until midnight, which is 24-bed_time/3600, and the time from midnight until wake_time, which is wake_time/3600, resulting in said formula.
What happens if we (incorrectly) apply the formula of case 2 to case 1? The correct, positive number of hours slept (for example, 7.5) is increased by 24 (result: 31.5 in the example).
Now the function f(x)=mod(x, 24) comes to the rescue because for a non-negative value x, written in the form 24*n+r with a non-negative integer n and a remainder r with 0<=r<24, it yields r. (Divide x by 24 to obtain the integer part n of the quotient and the remainder r, both uniquely determined.) That is, any additional integer multiple of 24, be it 24, 48 or 72, etc., is deducted while the remainder is left unchanged: f(x)=f(r)=r for all n=0, 1, 2, ...
In our application of f to the expression 24+(wake_time-bed_time)/3600 only two different values of n occur: n=0 for the correct result in case 2 (remember that wake_time-bed_time is negative here) and n=1 when the formula of case 2 is applied to case 1. So, the effect of function f just amounts to subtracting the incorrectly added 24 (hours) in the latter case, while the correct result in the former case is left unchanged. Hence we've found a single formula that is applicable to case 1 and case 2:
right_hours_slept = mod(24+(wake_time-bed_time)/3600,24)
... View more