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;

 

 

hackathon24-white-horiz.png

The 2025 SAS Hackathon Kicks Off on June 11!

Watch the live Hackathon Kickoff to get all the essential information about the SAS Hackathon—including how to join, how to participate, and expert tips for success.

YouTube LinkedIn

Creating Custom Steps in SAS Studio

Check out this tutorial series to learn how to build your own steps in SAS Studio.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

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