How to Convert Unix Datetime to SAS Datetime Format

This tutorial explains how to convert Unix Datetime to SAS Datetime format.

Method 1 : Adding Number of Seconds

A Unix datetime value starts from January 1, 1970. Whereas a SAS datetime value starts from January 1, 1960. To convert a Unix datetime value to a SAS datetime value, we can add the number of seconds between January 1, 1960 and January 1, 1970 i.e. 315619200 seconds. To display a variable in datetime format, we can use the PUT Function with datetime20. format.

data unix_to_datetime;
    unix_timestamp = 1692826529;
    
    /* Convert Unix timestamp to SAS datetime format */
    sas_datetime = put(315619200 + unix_timestamp, datetime20.);
    
    /* Print in LOG Window*/
    put "Unix Timestamp:" unix_timestamp;
    put "Formatted Datetime:" sas_datetime;
run;
proc print;
Convert Unix Datetime to SAS Datetime Format

Method 2 : dhms Function

We can use the dhms function to convert unix to SAS datetime format.

data unix_to_datetime;
    unix_timestamp = 1692826529;
    
    /* Convert Unix timestamp to SAS datetime format */
    sas_datetime = put(dhms('01jan1970'd, 0, 0, unix_timestamp), datetime20.);
    
    /* Print in LOG Window*/
    put "Unix Timestamp:" unix_timestamp;
    put "Formatted Datetime:" sas_datetime;
run;

To display the datetime in local time in SAS, we can use the TZONEOFF() function.

data unix_to_datetime;
    unix_timestamp = 1692826529;
    
    /* Convert Unix timestamp to SAS datetime format */
    sas_datetime = put(dhms('01jan1970'd, 0, 0, unix_timestamp + TZONEOFF()), datetime20.);
    
    /* Print in LOG Window*/
    put "Unix Timestamp:" unix_timestamp;
    put "Formatted Datetime:" sas_datetime;
run;
Result:
Unix Timestamp:1692826529
Formatted Datetime:24AUG2023:03:05:29

To display date in specific timezone, we can set the timezone using option TIMEZONE=.

option TIMEZONE='AUSTRALIA/MELBOURNE'; 
data unix_to_datetime;
    unix_timestamp = 1692826529;
    
    /* Convert Unix timestamp to SAS datetime format */
    sas_datetime = put(dhms('01jan1970'd, 0, 0, unix_timestamp + TZONEOFF()), datetime20.);
    
    /* Print in LOG Window*/
    put "Formatted Datetime:" sas_datetime;
run;

Output : Formatted Datetime:24AUG2023:08:35:29

Related Posts
Spread the Word!
Share
About Author:
Deepanshu Bhalla

Deepanshu founded ListenData with a simple objective - Make analytics easy to understand and follow. He has over 10 years of experience in data science. During his tenure, he worked with global clients in various domains like Banking, Insurance, Private Equity, Telecom and HR.

0 Response to "How to Convert Unix Datetime to SAS Datetime Format"

Post a Comment

Next → ← Prev