01-29-2016 12:21 PM
I have data source as below. It is read in as String. And I would like to convert it to time format. I tried the INPUT function using the TIMEAMPM5. format. It does not work. Any help? Much Thanks.
01-29-2016 01:46 PM - edited 01-29-2016 02:11 PM
data test; input tc & :$11.; /* Read time as character value tc. */ t=input(tc, ?? anydttme11.); /* Try to convert it using ANYDTTME11. informat. */ if cmiss(t, tc)=1 then do; /* If conversion failed, i.e., t is missing, but not tc, */ _i=indexc(upcase(tc), 'AP'); /* check if an 'A' or 'P' occurs in tc. */ if _i & ~index(tc, ':') then /* If this is the case, but no colon can be found in tc, */ tc=cats(substr(tc,1,_i-1),':00',substr(tc,_i)); /* insert ":00" before the 'A' or 'P'. */ t=input(tc, ?? anydttme11.); /* Try to convert the extended string. */ end; drop _i tc; format t time8.; /* optional formatting of SAS time value */ cards; 1AM 2AM 3AM 12AM 13AM 8:00AM 8PM 9 PM 19PM 29PM 10:00PM 11:34:56 PM ; proc print data=test; run;
As you can see, the above code is applicable not only to the format "HHAM/PM", but can be used to read other time formats as well (including unlikely values such as 13AM or 29PM).
Also, please note that the TIMEAMPM. format cannot be used to read data and currently (SAS 9.4) there seems to be no informat of this name.
01-29-2016 01:52 PM - edited 01-29-2016 06:51 PM
The time formats expect a minimum of 5 characters and your data is too short so you need to convert not read. Maybe one of these days SAS will allow an equivalent of a PICTURE for inputing values that allows date and time directives.
You will need to add a variable as a character can't be converted. Something like this might get you started.
data want; input texttime $;
i=index(upcase(texttime),'P')>0) *12; mytime = hms(input(compress(texttime,'APM'),best2.) +1,0,0);
drop i; format mytime timeampm5.; datalines; 1AM 2AM 3AM 10AM 1PM 2PM 11PM ; run;