Calcite | Level 5

## 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!

5 REPLIES 5
Opal | Level 21

## Re: Calculating number of hours from midnight

if ampm = "PM" then hours = time - 12; else hours = time;
PG
Super User

## Re: Calculating number of hours from midnight

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

## 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.

Obsidian | Level 7

## 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;

Calcite | Level 5

## 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;
Discussion stats
• 5 replies
• 1331 views
• 0 likes
• 5 in conversation