Hello,
I am trying to extract the month from a date value that looks like this
Date1
20080201
20080301
20080401
and I want to create a new variable that is
Date2
02
03
04
So i tried using
Date2=SUBSTR(Date1, 5, 2);
But it did not work. Can you help?
How do I do that?
phrases like 'it did not work' does not help us much. What differs from what you expect? What does the log say?
Help us help you 🙂
Do you have a character variable? Or a numeric? If a numeric does it have date values? Or just numbers like 20,200,801?
data have;
input
@1 date yymmdd8.
@1 char $8.
@1 num
;
format date yymmdd10.;
cards;
20080201
20080301
20080401
;
data want;
set have;
month_date = month(date);
month_char = substr(char,5,2);
month_num = int(mod(num,1E4)/1E2);
run;
month_ month_ month_ Obs date char num date char num 1 2008-02-01 20080201 20080201 2 02 2 2 2008-03-01 20080301 20080301 3 03 3 3 2008-04-01 20080401 20080401 4 04 4
In general it is easier/clearer to work with actual date values. So perhaps you want to convert character or non-date numerics to date first.
data want;
set have;
month_date = month(date);
month_char = month(input(char,yymmdd8.));
month_num = month(input(put(num,z8.),yymmdd8.));
run;
Since it is a date value (as you posted), just use the month() function.
Join us for SAS Innovate 2025, our biggest and most exciting global event of the year, in Orlando, FL, from May 6-9. Sign up by March 14 for just $795.
SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.
Find more tutorials on the SAS Users YouTube channel.