Reputation: 524
I want to determine to which 3-hour interval does time stamp belong to.
First interval ranges from 00:00:01
to 03:00:00
, second from 03:00:01
to 6:00:00
... Input is in format POSIXct
.
For example:
input: time<-Sys.time() #"2019-08-23 03:27:20 CEST"
output: 2
(Preferably fastest ways to do this)
Upvotes: 1
Views: 112
Reputation: 388817
We could use cut
by defining breaks
in a sequence of 3 hours and then convert it into integer.
as.integer(cut(time, breaks = seq(as.POSIXct("00:00:00", format = "%T"),
as.POSIXct("23:59:59", format = "%T"), by = "3 hours")))
and same with findInterval
findInterval(time, seq(as.POSIXct("00:00:00", format = "%T"),
as.POSIXct("23:59:59", format = "%T"), by = "3 hours"))
For the updated data shared, we can do
x <-structure(-62167133512, class = c("POSIXct", "POSIXt"), tzone = "UTC")
as.integer(cut(as.POSIXct(format(x, "%T"), format = "%T"),
breaks = seq(as.POSIXct(paste(Sys.Date(), "00:00:00")),
as.POSIXct(paste(Sys.Date() + 1, "00:00:00")), by = "3 hours")))
#[1] 8
Upvotes: 1