Hi,
I have a column like this
03JUN2016:00:00:00
16OCT2014:00:00:00
02MAY2016:00:00:00
12JAN2011:00:00:00
30MAR2017:00:00:00
20SEP2017:00:00:00
08MAR2016:00:00:00
13JUL2018:00:00:00
02FEB2011:00:00:00
26MAR2015:00:00:00
it is date variable.
I use codes to extract the year from it
PROC SQL NOEXEC; SELECT (YEAR(DATE(t1.DATO))) AS CALCULATION FROM WORK.RANDRANDOMSAMPLEQUERY_FOR_DV_ t1; QUIT;
What I got is:
2019
2019
2019
2019
2019
2019
2019
2019
2019
2019
which is obviously not right. Why???
correction
(YEAR(DATEPART(t1.DATO)))
Bascially datepart function extracts the sas date value from the sas datetime value. And year function takes effect on the sas date value which is the number of days from Jan1,1960
Test
data have;
input datetime :datetime20.;
format datetime datetime20.;
cards;
03JUN2016:00:00:00
16OCT2014:00:00:00
02MAY2016:00:00:00
12JAN2011:00:00:00
30MAR2017:00:00:00
20SEP2017:00:00:00
08MAR2016:00:00:00
13JUL2018:00:00:00
02FEB2011:00:00:00
26MAR2015:00:00:00
;
data want;
set have;
year=year(datepart(datetime));
run;
Or
proc sql;
create table want as
select *,year(datepart(datetime)) as year
from have;
quit;
Results
datetime | year |
---|---|
03JUN2016:00:00:00 | 2016 |
16OCT2014:00:00:00 | 2014 |
02MAY2016:00:00:00 | 2016 |
12JAN2011:00:00:00 | 2011 |
30MAR2017:00:00:00 | 2017 |
20SEP2017:00:00:00 | 2017 |
08MAR2016:00:00:00 | 2016 |
13JUL2018:00:00:00 | 2018 |
02FEB2011:00:00:00 | 2011 |
26MAR2015:00:00:00 | 2015 |
correction
(YEAR(DATEPART(t1.DATO)))
Bascially datepart function extracts the sas date value from the sas datetime value. And year function takes effect on the sas date value which is the number of days from Jan1,1960
Test
data have;
input datetime :datetime20.;
format datetime datetime20.;
cards;
03JUN2016:00:00:00
16OCT2014:00:00:00
02MAY2016:00:00:00
12JAN2011:00:00:00
30MAR2017:00:00:00
20SEP2017:00:00:00
08MAR2016:00:00:00
13JUL2018:00:00:00
02FEB2011:00:00:00
26MAR2015:00:00:00
;
data want;
set have;
year=year(datepart(datetime));
run;
Or
proc sql;
create table want as
select *,year(datepart(datetime)) as year
from have;
quit;
Results
datetime | year |
---|---|
03JUN2016:00:00:00 | 2016 |
16OCT2014:00:00:00 | 2014 |
02MAY2016:00:00:00 | 2016 |
12JAN2011:00:00:00 | 2011 |
30MAR2017:00:00:00 | 2017 |
20SEP2017:00:00:00 | 2017 |
08MAR2016:00:00:00 | 2016 |
13JUL2018:00:00:00 | 2018 |
02FEB2011:00:00:00 | 2011 |
26MAR2015:00:00:00 | 2015 |
You used the date() function, which always delivers the current date. As @novinosrin pointed out, use datepart().
Registration is now open for SAS Innovate 2025 , our biggest and most exciting global event of the year! Join us in Orlando, FL, May 6-9.
Sign up by Dec. 31 to get the 2024 rate of just $495.
Register now!
What’s the difference between SAS Enterprise Guide and SAS Studio? How are they similar? Just ask SAS’ Danny Modlin.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.