In SAS, the DATEPART() and TIMEPART() functions are used to extract the date and time parts from datetime values, respectively. Here’s how each function works:
1. DATEPART():
The DATEPART() function extracts the date part from a datetime value and returns it as a date value. This function is particularly useful when you have datetime values and need to perform date-specific operations without considering the time component.
Syntax:
DATEPART(datetime)
Example: Suppose you have a datetime variable datetime_var containing the value ’01Jan2022:12:30:45′, and you want to extract the date part from it. You can use the DATEPART() function as follows:
data output;
set input;
date_only = DATEPART(datetime_var);
run;
In this example, date_only will contain the date part ’01Jan2022′.
2. TIMEPART():
The TIMEPART() function extracts the time part from a datetime value and returns it as a time value. Similarly to DATEPART(), this function is useful when you need to perform time-specific operations without considering the date component.
Syntax:
TIMEPART(datetime)
Example: Suppose you have the same datetime variable datetime_var containing the value ’01Jan2022:12:30:45′, and you want to extract the time part from it. You can use the TIMEPART() function as follows:
data output;
set input;
time_only = TIMEPART(datetime_var);
run;
In this example, time_only will contain the time part ’12:30:45′.
3. HOUR():
The HOUR() function extracts the hour component from a datetime value and returns it as an integer value representing the hour of the day (0-23).
Syntax:
HOUR(datetime)
Example:
data output;
set input;
hour_of_day = HOUR(datetime_var);
run;
4. MINUTE():
The MINUTE() function extracts the minute component from a datetime value and returns it as an integer value representing the minute of the hour (0-59).
Syntax:
MINUTE(datetime)
Example:
data output;
set input;
minute_of_hour = MINUTE(datetime_var);
run;
5. SECOND():
The SECOND() function extracts the second component from a datetime value and returns it as an integer value representing the second of the minute (0-59).
Syntax:
SECOND(datetime)
Example:
data output;
set input;
second_of_minute = SECOND(datetime_var);
run;Additional Notes:
- Both
DATEPART()andTIMEPART()functions are part of Base SAS. - These functions are handy when dealing with datetime values in SAS, allowing you to perform specific operations on either the date or time component separately.
- The output of
DATEPART()is a SAS date value, while the output ofTIMEPART()is a SAS time value. - You can use the extracted date or time values for various purposes such as filtering, grouping, or calculations in your SAS programs.
Leave a Reply