I have a dataset full of times, indicating when an individual went to bed at night and when they woke up the next morning. I want to create a new variable that indicates the number of hours that they were asleep. However, SAS doesn't seem to understand how clocks work, and is unable to "wrap" times around the clock to do the calculation in a sensible way.
For example, if someone went to bed at 9pm and woke up at 5am, we would WANT the value of hours slept to be 8. However, SAS will return +/- 16, since it is only able to calculate the difference in a linear fashion. There are a couple of workarounds to this (included in my code snippet below), but they feel very clunky to me. One of them is pulling in the date variables and using the dhms function and then converting the result into hours, the other is converting the bedtime variable into the # of hours before midnight and then adding that to the wake up time variable.
Here's an example:
DATA time;
/* Bed time and wakey time */
bed_time = 75600; format bed_time time8.;
wake_time = 18000; format wake_time time8.;
/* Wrong answer */
wrong_hours_slept = intck('hour',bed_time,wake_time);
/* Clunky solution 1 */
day1 = today(); format day1 date8.;
day2 = intnx('day',day1,1); format day2 date8.;
seconds_slept = dhms(day2,0,0,wake_time) - dhms(day1,0,0,bed_time);
right_hours_slept1 = seconds_slept/3600;
/* Clunky solution 2 */
hours_before_midnight = (86400 - bed_time)/3600;
right_hours_slept2 = hours_before_midnight + wake_time/3600;
run;
Are there any other solutions? Obviously both of the above work, and ultimately don't require too much extra coding, but it feels rather frustrating to me that SAS doesn't have a built-in way of manipulating clock time. Further, both of these clunky solutions also have points of failure (notably with people who go to sleep after midnight), requiring some if/then logic to correct.
... View more