Desktop productivity for business analysts and programmers

Convert Data String to Date TIMEAMPM?

Reply
New User LLG
New User
Posts: 1

Convert Data String to Date TIMEAMPM?

Hi,

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.

 

1AM

2AM

3AM

1PM

2PM

Trusted Advisor
Posts: 1,114

Re: Convert Data String to Date TIMEAMPM?

[ Edited ]

Try this:

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.

Grand Advisor
Posts: 10,223

Re: Convert Data String to Date TIMEAMPM?

[ Edited ]

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;

 

 

Ask a Question
Discussion stats
  • 2 replies
  • 235 views
  • 0 likes
  • 3 in conversation