DATA Step, Macro, Functions and more

Calculating number of hours from midnight

Reply
Contributor
Posts: 29

Calculating number of hours from midnight

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!

Esteemed Advisor
Posts: 5,482

Re: Calculating number of hours from midnight

if ampm = "PM" then hours = time - 12; else hours = time;
PG
Super User
Posts: 9,913

Re: Calculating number of hours from midnight

[ Edited ]

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;
---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers
How to convert datasets to data steps
How to post code
PROC Star
Posts: 2,318

Re: Calculating number of hours from midnight

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.

 

Occasional Contributor
Posts: 15

Re: Calculating number of hours from midnight

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;

Contributor
Posts: 29

Re: Calculating number of hours from midnight

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;
Ask a Question
Discussion stats
  • 5 replies
  • 129 views
  • 0 likes
  • 5 in conversation