There is n number of ways to add Hours, Minutes and Seconds to a SAS
dataset. Out of those I will explain to you two ways to do this.
1.
Using datastep
2.
Using INTNX function
Consider the below dataset with time and datetime variables:
data mydata;
input mytime time. mydatetime datetime18.;
format mytime time. mydatetime datetime18.;
datalines;
12:00:00
02JAN1930:00:00:00
12:00:00
29APR2023:12:00:00
08:30:00 30APR2023:08:30:00
16:45:00
01MAY2023:16:45:00
21:15:00
02MAY2023:21:15:00
;
run;
Dataset:
To
add seconds, hours, and minutes to the above dataset, we can use the SAS datastep
or SAS INTNX function. The following are examples of how you can
do this.
1.
Adding hours to time variable using Datastep:
This code demonstrates how to manipulate time and time variables in the
SAS programming language using Datastep. You can apply the same logic over the datetime variable.
By doing so, we can easily add or subtract seconds, hours, and minutes
to these variables according to our needs.
data mydata;
set mydata;
mytime = mytime + '1:0:0't;
format mytime time.;
Keep mytime;
run;
Output:
2.
Adding minutes to datetime variable using INTNX function:
data mydata;
set mydata;
mydatetime = intnx('minute', mydatetime, 15);
format mydatetime datetime18.;
run;
Output:
Explain:
o
In this code, we use
the intnx function to add 15 minutes to the “mydatetime”
variable. The intnx function is taking an interval value as
minute and the number of intervals to add as 15.
o
Finally, we use the
format datetime18. to display the updated “mydatetime” variable in the datetime
format.
o
Similar to the
minutes used in this code. We can also use intervals such as “day”, “hour” and
“minute”.
More on INTNX function parameters: INTNX(Interval,
Date, n, Alignment, Weekstart, Method)
·
Interval: the type of interval to add or subtract, such as “day”, “hour”,
“minute”, etc.
·
Date: the starting date or datetime value to which the interval will be added
or subtracted.
·
n: the number of intervals to add or subtract.
·
Alignment: an optional parameter that specifies the alignment of the result, such
as BEGINNING, END, SAME etc.
·
Weekstart: an optional parameter that specifies the starting day of the week,
such as MON, TUE, etc.
·
Method: an optional parameter that specifies the method for handling daylight
saving time, leap years, etc.