BookmarkSubscribeRSS Feed
scolitti1
Calcite | Level 5

I have this dataset and I there is a variable that is in the DATETIME format and I want it in the DATE9. format.

 

My code: 

data a;
set casesdat.cases;
discharge = DatePart(Date_Discharged);
run;

 

data b;
set a;
format discharge date9.;
where '01jan2020'd <= discharge <= '20dec2020'd;
run;

 

The errors that come up:

Screenshot (2).png

 

I used a libname statement to read in the dataset and I double checked that the variables are in the right format with a proc contents. 

4 REPLIES 4
Reeza
Super User
Show the log from the prior set of code as well - I suspect there's an error that needs to be fixed first.
My guess is that date_discharged is character, not datetime but not sure.
PaigeMiller
Diamond | Level 26

You are getting these errors because variable DISCHARGE is character, it is not numeric, and so the formatting and WHERE statement will not work (these are expecting numeric values)

--
Paige Miller
Windata
Calcite | Level 5
You should specify the date9. format in the first data step - see below. Also, I think you can do the where clause in the same data step as well.

data a;
set casesdat.cases;
format discharge date9.;
discharge = DatePart(Date_Discharged);

where '01jan2020'd <= discharge <= '20dec2020'd;
run;
Tom
Super User Tom
Super User

@Windata wrote:
You should specify the date9. format in the first data step - see below. Also, I think you can do the where clause in the same data step as well.

data a;
set casesdat.cases;
format discharge date9.;
discharge = DatePart(Date_Discharged);

where '01jan2020'd <= discharge <= '20dec2020'd;
run;

You cannot reference the derived variable in the WHERE clause.  The where clause filters the data on the way into the data step, so it happens before DISCHARGE is created.

You could use a subsetting IF instead.

Or reference the original variable in the WHERE clause.  Either using appropriate datetime literals or using the DATEPART() function.

if '01jan2020'd <= discharge <= '20dec2020'd;
where '01jan2020:00:00'dt <= Date_discharged < '21dec2020:00:00'dt;
where '01jan2020'd <= datepart(Date_discharged) <= '20dec2020'd;

Ready to join fellow brilliant minds for the SAS Hackathon?

Build your skills. Make connections. Enjoy creative freedom. Maybe change the world. Registration is now open through August 30th. Visit the SAS Hackathon homepage.

Register today!
How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 4 replies
  • 762 views
  • 0 likes
  • 5 in conversation