SAS Programming

DATA Step, Macro, Functions and more
BookmarkSubscribeRSS Feed
corkee
Calcite | Level 5

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!

5 REPLIES 5
PGStats
Opal | Level 21
if ampm = "PM" then hours = time - 12; else hours = time;
PG
Kurt_Bremser
Super User

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;
ChrisNZ
Tourmaline | Level 20

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.

 

mahesh146
Obsidian | Level 7

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;

corkee
Calcite | Level 5

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-white.png

Special offer for SAS Communities members

Save $250 on SAS Innovate and get a free advance copy of the new SAS For Dummies book! Use the code "SASforDummies" to register. Don't miss out, May 6-9, in Orlando, Florida.

 

View the full agenda.

Register now!

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 5 replies
  • 2068 views
  • 0 likes
  • 5 in conversation