Hi,
I want to calculate the number of hours from midnight, with anything between 12 p.m. and 11:59 p.m. being negative. That is, 9 P.M. is “-3,”,while 6 A.M. is “6.” I tried the using something like the following, but I do not get the desired result. The variable I have is a time variable (12 hour clock), with another variable that indicates whether the time is in a.m. or p.m.
(fallaslp_mom_v2 - 60*60*12)/3600
Any suggestions would be great. Thank you!
if ampm = "PM" then hours = time - 12; else hours = time;
If you store your am/pm variable as a boolean value, it's a simple calculation:
data have;
input hour am_pm;
cards;
6 0
9 1
;
run;
data want;
set have;
your_hour = hour - 12 * am_pm;
run;
If it's character, justa a very small change is needed:
data want;
set have;
your_hour = hour - 12 * (am_pm = 'p.m.');
run;
You are not telling us everything it seems.
This works:
data WANT;
FALLASLP_MOM_V2= '09:00:00't;
AMPM = 'PM';
HOUR = (FALLASLP_MOM_V2 - 60*60*12*(AMPM='PM'))/3600;
run;
HOUR=-3
Also, the 24-hour clock is the way to go.
DATA TEMP;
INPUT D_TIME:time.;
FORMAT D_TIME midnight timeampm. Time_diff_midnight hhmm8.;
hr=hour(D_TIME);
%LET mid_night= %SYSFUNC(HMS(24,00,00));
midnight= &mid_night;
IF hr>=12 THEN Time_diff_midnight= D_TIME-&mid_night;
ELSE Time_diff_midnight=D_TIME;
CARDS;
12:30pm
11:10am
12:10am
5:10am
2:30pm
6:30pm
11:58pm
12:01am
;
RUN;
PROC PRINT DATA=TEMP;
Thank you, everyone. I figured out something similar to one of the proposed solutions--thankfully they match up!
proc sql;
create table survey as
select participant_id,
fallaslp,
fallaslpampm,
case
when fallaslpampm = 1 then fallaslp/3600
when fallaslpampm = 2 then (fallaslp - 60*60*12)/3600
end as fallaslp_newtime
from mydata
;
quit;
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.