SAS (Base SAS)+
*=============================================================================;
* Extract date and time parts from a datetime value
*=============================================================================;
*-----------------------------------------------------------------------------;
* Create sample lab data with datetime stamps
*-----------------------------------------------------------------------------;
data labs;
input usubjid $ lbtestcd $ lbdtm :datetime20.;
format lbdtm datetime20.;
datalines;
S001 ALT 15JAN2025:08:30:00
S001 AST 15JAN2025:14:15:30
S002 ALT 20FEB2025:09:00:00
S002 CREAT 20FEB2025:23:45:15
S003 ALT 01MAR2025:00:00:00
;
run;
*-----------------------------------------------------------------------------;
* Extract date portion, time portion, and individual components
*-----------------------------------------------------------------------------;
data lab_parts;
set labs;
* Extract the date part (SAS date value);
lbdt = datepart(lbdtm);
* Extract the time part (seconds since midnight);
lbtm = timepart(lbdtm);
* Extract individual time components;
lb_hour = hour(lbdtm);
lb_minute = minute(lbdtm);
lb_second = second(lbdtm);
format lbdt date9. lbtm time8.;
run;
proc print data=lab_parts noobs;
run;- We create a small lab dataset with datetime stamps in the SAS datetime literal format:
ddMONyyyy:hh:mm:ss. datepart(lbdtm)extracts the date portion and returns a SAS date value (days since 01JAN1960) β ready for merging or date arithmetic.timepart(lbdtm)extracts the time portion and returns the number of seconds since midnight β we format it withtime8.for display.hour(lbdtm),minute(lbdtm), andsecond(lbdtm)pull out individual time components as integers.- Subject S003 has a midnight timestamp (00:00:00); DATEPART still returns the correct date, and TIMEPART returns 0.
- Subject S002's second record at 23:45:15 tests the late-night edge: HOUR returns 23, not rolling over to the next day.
- The DATETIME20. informat reads the full datetime literal; if we only need the date, it is more efficient to store dates as SAS date values from the start.
- We run PROC PRINT and confirm that the extracted date and time parts reconstruct the original datetime when combined.