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().
Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!
Check out this tutorial series to learn how to build your own steps in SAS Studio.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.