[R] converting a time to nearest half-hour

Gabor Grothendieck ggrothendieck at gmail.com
Fri Jul 23 18:48:03 CEST 2010


On Fri, Jul 23, 2010 at 12:35 PM,  <Murali.Menon at avivainvestors.com> wrote:
> David, Stephen,
> You're right - it's the time zone conventions that threw me as well. I tried those round() operations earlier, but inevitably ended up being either an hour behind. Even when I specified my time zone, it didn't make any difference. So there's something else that I'm missing. I'll take a look at your various approaches, and get back to you.

Does your problem really involve time zones?  If not you would likely
be best off using a datetime class that has no time zone so you don't
run into this problem in the first place.  Also its particularly easy
with chron due to the availability of trunc.times() :

   library(chron)
   now <- as.chron(format(Sys.time()))

   trunc(now + as.numeric(times("00:15:00")), "00:30:00")

With POSIXct you could muck with the internals like this (which uses
the fact that there are 1800 seconds in an half hour):

   x <- Sys.time()
   structure(1800 * (as.numeric(x + 900) %/% 1800), class = class(x))

See the article in R News 4/1 for more.



More information about the R-help mailing list