DATA Step, Macro, Functions and more

Convert Character to Date

Reply
Contributor
Posts: 21

Convert Character to Date

I have a character variable with parameters format=$char19. informat=$char19. that I would would like to convert to datetime. Below are the examples of variables:

 

Aug 24 2017 12:11PM

Dec  7 2017  2:12PM

May 28 2014  3:55PM

 

I believe I only need to use the input function. May I know what informat should I use? I tried these but it seems that I'm getting the wrong value

 

numeric=input('Feb 6 2015 4:51PM',ANYDTDTM19.);

numeric=input('Feb 6 2015 4:51PM',ANYDTTME19.);

Super User
Super User
Posts: 9,599

Re: Convert Character to Date

I am pretty sure that some people go out of their way to make dates as difficult to read as possible.  I would do:

data have;
  text="Aug 24 2017 12:11PM"; output;
  text="Dec  7 2017  2:12PM"; output;
run;

data want (drop=tmp_:);
  set have;
  tmp_date=input(cats(substr(text,5,2),substr(text,1,3),substr(text,8,4)),date9.);
  tmp_time=input(strip(substr(text,12,6)),time5.);
  want=dhms(tmp_date,hour(tmp_time),minute(tmp_time),0);
  format want datetime.;
run;

Well, I would probably go back to source and change that into a usable format myself...

Super User
Posts: 10,279

Re: Convert Character to Date

[ Edited ]

Your idea of using the anydtdtm informat works:

data want;
input indate anydtdtm19.;
format indate dateampm22.;
cards;
Aug 24 2017 12:11PM
Dec  7 2017  2:12PM
May 28 2014  3:55PM
;
run;

proc print data=want noobs;
run;

Result:

               indate

24AUG2017:12:11:00 PM
07DEC2017:02:12:00 PM
28MAY2014:03:55:00 PM

 

Edit: increased length of display format from 20 to 22 to get a 4-digit year.

---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers
How to convert datasets to data steps
How to post code
Ask a Question
Discussion stats
  • 2 replies
  • 55 views
  • 0 likes
  • 3 in conversation