DATA Step, Macro, Functions and more

How to extract year and month from date in SAS?

Accepted Solution Solved
Reply
Frequent Contributor
Posts: 99
Accepted Solution

How to extract year and month from date in SAS?

I have date variables in the form of YYYY-MM-DD, stored in tables.

 

How do I extract the Year?

 

Basically I just want to do a simple SQL 

such as, select * from table where YEAR(date) = 2017;

 

Thanks!


Accepted Solutions
Solution
‎03-09-2017 08:21 PM
Regular Contributor
Posts: 194

Re: How to extract year and month from date in SAS?

[ Edited ]

Hello,

the function you are looking for is year() as you guessed correctly, but your data has to be in

a date format.

 

data have;
format dt yymmdd10.;
input dt yymmdd10.;
datalines;
2016-05-21
2017-08-12
2014-03-02
;
run;

data want;
set have;
where year(dt)=2017;
run;

Edit: If you have strings instead :

data want;
set have;
where year(input(dt,yymmdd10.))=2017;
run;

View solution in original post


All Replies
Solution
‎03-09-2017 08:21 PM
Regular Contributor
Posts: 194

Re: How to extract year and month from date in SAS?

[ Edited ]

Hello,

the function you are looking for is year() as you guessed correctly, but your data has to be in

a date format.

 

data have;
format dt yymmdd10.;
input dt yymmdd10.;
datalines;
2016-05-21
2017-08-12
2014-03-02
;
run;

data want;
set have;
where year(dt)=2017;
run;

Edit: If you have strings instead :

data want;
set have;
where year(input(dt,yymmdd10.))=2017;
run;
Super User
Super User
Posts: 7,413

Re: How to extract year and month from date in SAS?

Are you sure its a SAS numeric date, i.e. it is a number if you remove the format.  If so then year(), if it is character which I suspect, then just use:

where scan(date,1,"-")="2017";

 

Frequent Contributor
Posts: 99

Re: How to extract year and month from date in SAS?

The date is in this format YYMMDD10. 

Frequent Contributor
Posts: 99

Re: How to extract year and month from date in SAS?

Can I create a new column year within proc sql?

 

proc sql;
select input(thedate,yymmdd10.) as myyear
from mytable;
quit;

 

I tried this but doesn't seem to work.

☑ This topic is solved.

Need further help from the community? Please ask a new question.

Discussion stats
  • 4 replies
  • 2028 views
  • 1 like
  • 3 in conversation