Desktop productivity for business analysts and programmers

Change all time variables to nearest hour

Reply
Contributor
Posts: 58

Change all time variables to nearest hour

Folks,

 

I've a number of time variables in the following example time8. format; 17:34:34, 09:07:00.

 

What I would like to do is change them all to the nearest hour i.e. 17:00:00 and 09:00:00.

 

Is it possible to do this in an array similar to how you would do it for month variables e.g. 

 

array datevars {*} intdate1  previntdate;
do i=1 to dim(datevars);
datevars{i} = intnx('month',datevars{i},0,'begin');
end;

Any help is most welcome.

Community Manager
Posts: 3,448

Re: Change all time variables to nearest hour

Posted in reply to Sean_OConnor

From your example, it looks like you want to "round down" to the hour the value is in, not necessarily the "nearest" hour boundary, right?

 

data _null_;
 x = intnx('hour', '05FEB2010:17:34:43'dt, 0, 'b'); 
 y = intnx('hour', '17:34:43't, 0, 'b');
 format x datetime20. y time8.;
 put x= y=;
run;

 

Output:

 

x=05FEB2010:17:00:00 y=17:00:00
Super User
Super User
Posts: 9,799

Re: Change all time variables to nearest hour

[ Edited ]
Posted in reply to Sean_OConnor

Or maybe simpler:

want=hour(timevar) * (60 * 60);

I.e. take the hour and multiple it by minutes and seconds to get a time value.

 

 

Is it time variables you are dealing with or dates, as your question about time values does not match the example which uses date variables?  If its just time then:

want=input(cats(put(hour(timevar),z2.),":00:00"),tod11.);

 

Just chops off the min/sec and adds 00 again.

 

Super User
Posts: 10,528

Re: Change all time variables to nearest hour

Posted in reply to Sean_OConnor

Since SAS time and datetime values are counts of seconds, this will also work:

timevar = int(timevar/3600) * 3600;
---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers
How to convert datasets to data steps
How to post code
Ask a Question
Discussion stats
  • 3 replies
  • 161 views
  • 0 likes
  • 4 in conversation