BookmarkSubscribeRSS Feed
LLG
Calcite | Level 5 LLG
Calcite | Level 5

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

2 REPLIES 2
FreelanceReinh
Jade | Level 19

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.

ballardw
Super User

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;

 

 

sas-innovate-2024.png

Join us for SAS Innovate April 16-19 at the Aria in Las Vegas. Bring the team and save big with our group pricing for a limited time only.

Pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.

 

Register now!

SAS Enterprise Guide vs. SAS Studio

What’s the difference between SAS Enterprise Guide and SAS Studio? How are they similar? Just ask SAS’ Danny Modlin.

Find more tutorials on the SAS Users YouTube channel.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 2 replies
  • 994 views
  • 0 likes
  • 3 in conversation