elemarles
elemarles

Reputation: 27

Problems with creating Time variable in SAS

I'm traying to put together a time in HH:MM:SS AM/PM because I have the hours, mins and AM/PM separate in 3 different variables. My dataset looks like this:

hr_bedhr  hr_bedmin  hr_bedampm
10        0          PM
10        30         PM
12        55         AM

And I would like the output to look like this:

hr_bedhr  hr_bedmin  hr_bedampm  bedtime
10        0          PM          22:00:00
10        30         PM          22:30:00
12        55         AM          00:55:00

I've tried several codes but they don't seem to be working. Here are some codes that I've tried.

data want; set have;
put (hr_bedhr, time8.);run;

This one gives back 0:00:10 when in reality it should be 10:00:00 if we take as example the first row of data.

Thanks for the help!

Upvotes: 0

Views: 308

Answers (2)

Reeza
Reeza

Reputation: 21264

A different method - add 12 if it's PM and use the HMS() function.

IFN checks if it's AM/PM then adds 12 to hour and passes that value to the HMS function.

data have ;
  input hr_bedhr  hr_bedmin  hr_bedampm $;
cards;
10        0          PM
10        30         PM
12        55         AM
;

data want;
  set have;
  time = hms(hr_bedhr+ ifn(hr_bedampm='PM', 12, 0), hr_bedmin, 0);
  format time tod8.;
run;

Upvotes: 0

Tom
Tom

Reputation: 51566

Just combine them with a space between the values and use the TIME informat.

data have ;
  input hr_bedhr  hr_bedmin  hr_bedampm $;
cards;
10        0          PM
10        30         PM
12        55         AM
;

data want;
  set have;
  time = input(catx(' ',hr_bedhr,hr_bedmin,hr_bedampm),time8.);
  format time tod8.;
run;

Results:

Obs    hr_bedhr    hr_bedmin    hr_bedampm        time

 1        10            0           PM        22:00:00
 2        10           30           PM        22:30:00
 3        12           55           AM        00:55:00

Upvotes: 2

Related Questions