Reputation: 45
I am trying to calculate the length of time that a person sleeps. My dataset includes the following variables: SleepHour
, SleepMinute
, SleepAM_PM
, WakeHour
, WakeMinute
, and WakeAM_PM
. The hour variable ranges from 1-12, the minute variable ranges from 0-59, and the AM/PM variable is binary (1 = AM; 2 = PM).
I tried the following code and it was close but it didn't account for the fact that minutes are measured on a 60-point scale, so a person who sleeps at 11:00pm and wakes at 6:30am was listed as getting 7.70 hours of sleep, although it should be 7.30.
* Calculate time spent asleep with decimal places.
COMPUTE SleepMilitaryTime = 0.
COMPUTE WakeMilitaryTime = 0.
COMPUTE SleepDuration = 0.
* Convert sleep time to military time.
IF (SleepAM_PM = "PM" & SleepHour < 12) SleepMilitaryTime = (SleepHour + 12) * 100 + SleepMinute.
IF (SleepAM_PM = "AM" & SleepHour = 12) SleepMilitaryTime = SleepMinute.
IF (SleepAM_PM = "AM" & SleepHour < 12) SleepMilitaryTime = SleepHour * 100 + SleepMinute.
* Convert wake time to military time.
IF (WakeAM_PM = "PM" & WakeHour < 12) WakeMilitaryTime = (WakeHour + 12) * 100 + WakeMinute.
IF (WakeAM_PM = "AM" & WakeHour = 12) WakeMilitaryTime = WakeMinute.
IF (WakeAM_PM = "AM" & WakeHour < 12) WakeMilitaryTime = WakeHour * 100 + WakeMinute.
* Calculate sleep duration with decimal places.
IF (WakeMilitaryTime >= SleepMilitaryTime) SleepDuration = (WakeMilitaryTime - SleepMilitaryTime) / 100.
IF (WakeMilitaryTime < SleepMilitaryTime) SleepDuration = ((2400 + WakeMilitaryTime) - SleepMilitaryTime) / 100.
EXECUTE.
I also tried using the SPSS Date and Time Wizard, but I think that works only when the hours are in 24-hour time and these are not.
If you know how to solve this problem, I would be very grateful!!
Upvotes: 1
Views: 331
Reputation: 11360
You don't mention having a date, so the following code covers for it by adding 24 to the waking time if needed, before calculating the total sleep time":
* first calculate one number for sleep and for wake time.
recode SleepHour WakeHour (12=0).
compute slp = SleepHour + (SleepMinute/60) + 12*(SleepAM_PM=2).
compute wak = WakeHour + (WakeMinute/60) + 12*(WakeAM_PM=2).
* now since we don't have the date we assume that since wake
time is later than sleep time, it is either bigger than
sleep time, or smaller - in the next day.
if wak < slp wak = wak + 24.
* now we're ready to calculate total sleep time in hours.
compute totalSleepTime = wak - slp.
execute.
Upvotes: 0