DATA Step, Macro, Functions and more

How to change year of datetime ?

Reply
Contributor
Posts: 43

How to change year of datetime ?

All, 
     I am looking for help on changing the year of datetime column in a SAS dataset. 

 

image.png
I have provided a screenshot of the column. I would like to learn 2 things : 

1. How can I change the year of the datetime column shown above ? 
2. How can I generate timestamps for nth year from the given column ? (I am trying to do it for 6th and 11th years) 

%Do i = 1 %To 2; 
%Let YearInterval = %Eval(&i.*5 + 1);
Proc SQL INOBS = 8760; Create Table Work.Want As Select DHMS(MDY(MONTH(DATEPART(Timestamp__yyyy_MM_dd_HH_mm_ss_)),
DAY(DATEPART(Timestamp__yyyy_MM_dd_HH_mm_ss_)),
YEAR(DATEPART(Timestamp__yyyy_MM_dd_HH_mm_ss_))+ &YearInterval),0,0,timepart(Timestamp__yyyy_MM_dd_HH_mm_ss_))
as Timestamp__yyyy_MM_dd_HH_mm_ss_ From Work.Have; Quit;
%End;

 



Contributor
Posts: 31

Re: How to change year of datetime ?

Posted in reply to UdayGuntupalli

Check out the function INTNX.

From this useful page:

INTNX( 'datetime-interval', datetime, n <, 'alignment'> )

returns the date or datetime value of the beginning of the interval that is n intervals from the interval that contains the given date or datetime value. The optional alignment argument specifies that the returned date is aligned to the beginning, middle, or end of the interval. Beginning is the default. In addition, you can specify SAME (S) alignment. The SAME alignment bases the alignment of the calculated date or datetime value on the alignment of the input date or datetime value. As illustrated in the following example, the SAME alignment can be used to calculate the meaning of "same day next year" or "same day two weeks from now."

   nextYear = INTNX( 'YEAR', '15Apr2007'D, 1, 'S' );
   TwoWeeks = INTNX( 'WEEK', '15Apr2007'D, 2, 'S' );

The preceding example returns '15Apr2008'D for nextYear and '29Apr2007'D for TwoWeeks.

For all values of alignment, the number of discrete intervals n between the input date and the resulting date agrees with the input value. In the following example, the result is always that n2 = n1:

   date2 = INTNX( interval, date1, n1, align );
   n2 = INTCK( interval, date1, date2 );

The preceding example uses the DISCRETE method of the INTCK function by default. The result n2 = n1 does not always apply when the CONTINUOUS method of the INTCK function is specified.

 

Super User
Posts: 24,004

Re: How to change year of datetime ?

Posted in reply to Urban_Science
Because it’s date time variable, your interval should be DTYEAR.
Ask a Question
Discussion stats
  • 2 replies
  • 74 views
  • 0 likes
  • 3 in conversation