Using SAS 9.4
How do I convert a character time variable to a SAS time variable? Examples of my time variable are below. The time could be 5 or 6 digits before the am/pm in my data. Thank you
"122300 PM"
"91300 AM"
"82500 AM"
I think you will have to read the first part using HHMMSS informat than then manually add 12 hours when appropriate.
data test;
input string $char10.;
time=input(string,hhmmss6.);
if time < '12:00't and find(string,'PM','i') then time+'12:00't;
format time tod8. string $quote.;
put time string ;
cards;
122300 PM
91300 AM
91300 pm
82500 AM
82500 AM
;
Results
12:23:00 "122300 PM" 09:13:00 "91300 AM" 21:13:00 "91300 pm" 08:25:00 "82500 AM" 08:25:00 " 82500 AM"
If you want a expression you use that avoids the IF/THEN try this one. It will read in the [h]hmmss string part and then put it using TOD format and append the AM/PM suffix and then read the whole result using the TIME informat that recognizes the AM/PM.
time=input(put(input(string,hhmmss6.),tod8.)||scan(string,2,' '),time12.);
Hello @GS2 ,
What do the numbers represent?
There are only 24*60*60=86400 seconds in a day?
Hence, the below is probably NOT what you are looking for.
data _NULL_;
LENGTH A $ 10 b 8;
a="122300 PM"; b=input(scan(a,1),6.); put b= time8.;
a="91300 AM"; b=input(scan(a,1),6.); put b= time8.;
a="82500 AM"; b=input(scan(a,1),6.); put b= time8.;
run;
Koen
I think you will have to read the first part using HHMMSS informat than then manually add 12 hours when appropriate.
data test;
input string $char10.;
time=input(string,hhmmss6.);
if time < '12:00't and find(string,'PM','i') then time+'12:00't;
format time tod8. string $quote.;
put time string ;
cards;
122300 PM
91300 AM
91300 pm
82500 AM
82500 AM
;
Results
12:23:00 "122300 PM" 09:13:00 "91300 AM" 21:13:00 "91300 pm" 08:25:00 "82500 AM" 08:25:00 " 82500 AM"
If you want a expression you use that avoids the IF/THEN try this one. It will read in the [h]hmmss string part and then put it using TOD format and append the AM/PM suffix and then read the whole result using the TIME informat that recognizes the AM/PM.
time=input(put(input(string,hhmmss6.),tod8.)||scan(string,2,' '),time12.);
data test; input string $20.; _string=prxchange('s/(\d?\d)(\d\d)(\d\d)/\1:\2:\3/',1,string); time=input(_string,anydttme32.); format time tod8. string $quote.; cards; 122300 PM 91300 AM 91300 pm 82500 AM 82500 AM ;
Available on demand!
Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.