BookmarkSubscribeRSS Feed
floflow
Calcite | Level 5

Hi, 

 

I currently have 2 numeric columns with times in am and pm and i am trying to calculate sleep duration.

 

I have no idea where to start. 

 

Can someone help? Thanks so much in advance!

 

3 REPLIES 3
PaigeMiller
Diamond | Level 26

Numeric column with time values: you can just do a subtraction to get the time difference, then divide this difference by the number of seconds in an hour to get hours.

 

NOTE: if the times were collected on different days, for example on 20SEP2022 the person went to sleep at 2200 and woke up the 21SEP2022 at 0600, then you would need to use datetime values in SAS, not time values, but the solution is the same.

--
Paige Miller
PGStats
Opal | Level 21

Or if your SAS times refer to consecutive days, use the expression:

 

sleepSeconds = endTime - startTime + "24:00:00"t;

 

Note: "24:00:00"t is a SAS time literal that represents the number of seconds in 24 hours.

PG
Tom
Super User Tom
Super User

SAS stores TIME values as number of seconds.  So you can subtract to get the difference in seconds.  You could use a TIME type format to display that.  If you actually want to convert to a number of hours then just divide by the number of seconds in an hour.

 

If you only have time of day readings (and not full datetime readings) then you probably need to be sure they represent time from different days.  If you can assume that none of the observations represent intervals longer than 24 hours that test is just whether the beginning time of day is before the ending time of day.  If the wake time of day is less than the sleep time of day then that means they woke on the NEXT day.  So you can take advantage of the fact that datetime values are also in stored in seconds and that SAS returns zero for FALSE boolean expressions and one for TRUE boolean expressions.

 

Example:

data have ;
  input id sleep :time. wake :time. ;
  format sleep wake tod8. ;
cards;
1 10:00pm 06:00am
2 03:00pm 11:00pm
3 11:00 11:00 
;

proc print;
run;

data want;
  set have;
  seconds = dhms(wake<sleep,0,0,wake) - dhms(0,0,0,sleep) ;
  hours = seconds/'01:00:00't ;
  format seconds time12.;
run;

proc print;
run;

Results:

Tom_0-1663827946582.png

 

 

sas-innovate-2024.png

Available on demand!

Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.

 

Register now!

What is ANOVA?

ANOVA, or Analysis Of Variance, is used to compare the averages or means of two or more populations to better understand how they differ. Watch this tutorial for more.

Find more tutorials on the SAS Users YouTube channel.

Discussion stats
  • 3 replies
  • 349 views
  • 2 likes
  • 4 in conversation