SAS9

How to Get the Current Date and Time

Simon 15 vistas

The Problem with &SYSDATE

If you regularly work with SAS©, you have probably already used the automatic macro variable &SYSDATE. However, a specific behavior can surprise users: &SYSDATE does not store the current date, but the start date of the SAS© session.

If you start SAS© on Monday and leave your session open until Friday, &SYSDATE will still show Monday's date. The only way to update this variable is to restart SAS©, which is not ideal for automated processes or long work sessions.

So, how do you get the exact date or time at the moment of execution without logging off?


The Solution: The %SYSFUNC Function

The most robust method for obtaining a dynamic value (updated in real-time) is to use the macro function %SYSFUNC. It allows you to execute standard SAS© functions (like today(), time(), or datetime()) directly in the macro language.

Here are the different methods for retrieving this information, whether for creating macro variables or for using them directly in the code.

Note :
1. Get the Current Date (TODAY)
To get the current date, use the today() function.

Option A: Create a macro variable (raw value) This stores the date as a number (the number of days since 01/01/1960). Useful for calculations.
1%let today_raw = %sysfunc(today());
2 
3/* Résultat exemple : 23456 */
Note :
Option B: Create a macro variable (formatted) If you need a readable date (e.g., for a report title or a filename), add a format as the second argument in %sysfunc.
1%let today_str = %sysfunc(today(), date9.);
2 
3/* Résultat exemple : 19DEC2025 */
Note :
Option C: Direct use in a Data step or PROC SQL You don't need a macro variable if you are already in a Data step.
1DATA _null_;
2 current_date = today();
3 put current_date date9.;
4RUN;
Note :
Get the Full Date and Time (DATETIME)
If you need more precision (the exact time or the full timestamp), the logic is the same.

For the full timestamp (Date + Time):
1/* Valeur brute (secondes depuis 1960) */
2%let dt_raw = %sysfunc(datetime());
3 
4/* Valeur formatée (lisible) */
5%let dt_str = %sysfunc(datetime(), datetime20.);
6/* Résultat exemple : 19DEC2025:17:05:35 */

Do not rely on &SYSDATE or &SYSTIME if your process requires the precise execution time, especially in server environments or SAS© Enterprise Guide sessions that remain open for a long time. Always prefer %sysfunc(today()) or %sysfunc(datetime()) to ensure the accuracy of your time data.