Convert a Date into a DateTime Variable
In SAS exist Date and DateTime variables. If you want to compare them, they should be of the same type. This article explains how to transform a Date variable into a DateTime variable with the DHMS function. The article also contains some useful examples.
The DHMS syntax
DHMS(date, hour, minute, second)
The DHMS function exists of four obligatory arguments:
- date: This is the date part of the DateTime variable.
- hour: The hour of the DateTime variable.
- minute: The minute of the DateTime variable.
- second: The second of the DateTime variable.
All arguments can be existing variables or numbers. Besides that, the date argument can also be a constant that can be interpreted by SAS as a date (see example).
SAS Code & Examples
Below you find an example of how to convert a Date variable into a DateTime variable. The example also shows how to create a DateTime variable where the date argument is a constant that SAS interprets as a Date.
DATA WORK.DS; SET SASHELP.BUY (DROP= AMOUNT); /* CREATE DATETIME VARIABLES */ MY_DATETIME_12PM = DHMS(DATE,0,0,0); MY_DATETIME_1630 = DHMS(DATE,16,30,0); /* CREATE DATETIME VARIABLE */ MY_DATETIME = DHMS("15JUN2020"D,22,30,00); /* FORMAT DATETIME VARIABLES */ FORMAT MY_DATETIME: DATETIME20.; RUN;
Remember, since both Date and DateTime variables in SAS are in fact numbers, it’s necessary to format the new variables to make them easier to interpret.