sas informat datetime

Allan Bowe picture Allan Bowe · Sep 7, 2009 · Viewed 7.7k times · Source

Can anyone advise on the appropriate SAS informat to read in a datetime (dd/mm/yyyy hh:mm) ???

eg

data _null_;
informat from_dt datetime????.;
input from_dt ;
put from_dt=;
cards;
01/01/1960 00:00
;run;

Answer

cmjohns picture cmjohns · Sep 8, 2009

I don't think that specific informat is built-in, but it is relatively easy to roll your own. Below is an example of a creating a custom datetime informat (this requires a cntlin data set) and a custom format (using the picture statement) that reads in your specific datetime and then formats it back out to look the same as the input. I simplified it by assuming the time part was always midnight (00:00), but it can be easily expanded if you need to keep track of the time parts as well (just change the 86400 number to 3600 to get every hour, and 60 for every minute). It helps to see what is going on if you open the work.infmt data set to see what it looks like.

/* Create a custom datetime format as Month/Day/Year<space>Hours:Minutes*/
proc format;
  picture mydt other='%0m/%0d/%0Y %0H:%0M' (datatype=datetime);
run;

/* Create a custom informat using the format above */
data infmt ;
retain fmtname "dtwithspace" type "I" ;
   do label = "1jan1960:00:00"dt to
              "2jan2059:00:00"dt by 86400 ; 
      start = trim(left(put(label,mydt.)));
      output ;
   end ;
run ;
proc format cntlin = infmt ;
run ;


/* Now apply the informat and format to the data */
data _null_;
input from_dt $ 1-20;
format from_dt2 mydt.;
from_dt2=input(from_dt, dtwithspace.);
put from_dt2=;
cards;
01/01/1960 00:00
01/02/1999 00:00
;
run;

This gave an output like this:

278  data _null_;
279  input from_dt $ 1-20;
280  format from_dt2 mydt.;
281  from_dt2=input(from_dt, dtwithspace.);
282  put from_dt2=;
283  cards;

from_dt2=01/01/1960 00:00
from_dt2=01/02/1999 00:00