4.2 C
London
Friday, December 20, 2024
HomeSASData Munging in SASHow to Convert Datetime to Date in SAS

How to Convert Datetime to Date in SAS

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

The easiest way to convert a datetime to a date in SAS is to use the DATEPART function.

This function uses the following basic syntax:

date = put(datepart(some_datetime), mmddyy10.);

The argument mmddyy10. specifies that the date should be formatted like 10/15/2022.

The following example shows how to use this syntax in practice.

Example: Convert Datetime to Date in SAS

Suppose we have the following dataset in SAS that contains one column of datetimes:

/*create dataset*/
data original_data;
    format some_datetime datetime23.;
    input some_datetime :datetime23.;
    datalines;
14OCT2022:0:0:0
09NOV2022:0:0:0
14NOV2022:0:0:0
15NOV2022:0:0:0
22DEC2022:0:0:0
24DEC2022:0:0:0
04JAN2023:0:0:0
;
run;

/*view dataset*/
proc print data=original_data;

The following code shows how to use the DATEPART function to create a new dataset in which the values in the datetime column are formatted as dates with various formats:

/*create new dataset with datetime formatted as date*/
data new_data;
    set original_data;
    date_mmddyyyy = put(datepart(some_datetime), mmddyy10.);
    date_yyyymmdd = put(datepart(some_datetime), yymmdd10.);
    date_date9 = put(datepart(some_datetime), date9.);
    date_default = datepart(some_datetime);
run;

/*view new dataset*/
proc print data=new_data;

Notice that the four new columns display the date from the original datetime column in various formats.

By default, the DATEPART function converts a datetime to the number of days since January 1, 1960.

Thus, the new column called date_default displays the number of days since January 1, 1960 for each datetime.

Note: You can find the complete documentation for the SAS DATEPART function here.

Additional Resources

The following tutorials explain how to perform other common tasks in SAS:

How to Add Days to Date in SAS
How to Convert Numeric Variable to Date in SAS
How to Calculate Difference Between Two Dates in SAS

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories