How to convert YYYY-MM-DDTHH:MM format to datetime16. format ?
I have below data where some of them doesn't have timepart. I need to convert this data to datetime16. format
2012-07-26
2012-07-26T15:41
2012-07-26T15:55
2012-08-08
Can someone please teach me ?
Hi @bobbyc,
Try this:
data test;
input;
dt=input(translate(_infile_,':','T'), anydtdtm.);
format dt datetime16.;
cards;
2012-07-26
2012-07-26T15:41
2012-07-26T15:55
2012-08-08
;
This creates a SAS datetime value which you can format with DATETIME16. (as shown above) or any other suitable format. Missing time parts are imputed as 00:00:00.
Edit: If your data are already in a SAS dataset, say olddt='2012-07-26T15:41', you can transform them similarly:
dt=input(translate(olddt,':','T'), anydtdtm.);
Reinhard,
I like to have control over my conversions, so I test the values:
data dt ;
length dtc $ 30
dtf $ 3
;
input dtc ;
if prxmatch( "/^\d{4,4}-\d{2,2}-\d{2,2}$/" , strip( dtc ))
then
do ;
dt = input( cats( dtc , "T00:00:00" ) , e8601dt. ) ;
dtf = "HMS" ;
end ;
else if prxmatch( "/^\d{4,4}-\d{2,2}-\d{2,2}T\d{2,2}:\d{2,2}$/" , strip( dtc ))
then
do ;
dt = input( cats( dtc , ":00" ) , e8601dt. ) ;
dtf = "S" ;
end ;
datalines ;
2012-07-26
2012-07-26T15:41
2012-07-26T15:55
2012-08-08
run ;
proc print data = dt ;
format dt datetime16. ;
run ;
A few points: it is worth emphasizing that SAS datetimes variables are just a number. How you present that number is controlled by the format. The datetime is at least as refined as seconds, so all of these values are truncated. I include a flag to indicate the level of imputation (I choose "00", but you could also use any value to "59", but SAS will round for the DATETIME16. format). Some standards might represent "HMS" as "H", because if you imputated hours, then minutes and seconds were missing, too (presumably). Lastly, the regular expressions are too broad, but serve for some data.
HTH,
Kevin
Sorry, I should have addressed the OC, bobbyc, not Rienhard.
-Kevin
Use the informat of B8601DT.
Nice! Great improvement.
Thanks,
Kevin
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 16. Read more here about why you should contribute and what is in it for you!
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.
Select SAS Training centers are offering in-person courses. View upcoming courses for: