Reputation: 5789
Consider the date:
options(digits.secs = 6)
library(lubridate)
this_special_date <- with_tz(as.POSIXct(strptime('2017-11-20 23:00:00.051438000',
'%Y-%m-%d %H:%M:%OS', tz = 'GMT')),
tzone='Asia/Tokyo')
Now, I can use the function myformat.POSIXct
from this answer to round it to the nearest milisecond:
myformat.POSIXct <- function(x, digits=0) {
x2 <- round(unclass(x), digits)
attributes(x2) <- attributes(x)
x <- as.POSIXlt(x2)
x$sec <- round(x$sec, digits) + 10^(-digits-1)
format.POSIXlt(x, paste("%Y-%m-%d %H:%M:%OS",digits,sep=""))
}
myformat.POSIXct(this_special_date, digits=3)
return: "2017-11-21 08:00:00.051". But how to round a POSIXct time to the next miliseconds? --i.e. in the case above it would be "2017-11-21 08:00:00.052".
Upvotes: 0
Views: 111
Reputation: 461
Could you add 00.0005 to all values? This would ensure that they are always rounded up relative to the starting value.
myformat.POSIXct <- function(x, digits=0) {
x2 <- round(unclass(x + (5*10^(-digits-1))), digits)
attributes(x2) <- attributes(x)
x <- as.POSIXlt(x2)
x$sec <- round(x$sec, digits) + 10^(-digits-1)
format.POSIXlt(x, paste("%Y-%m-%d %H:%M:%OS",digits,sep=""))
}
myformat.POSIXct(this_special_date, digits=3)
Upvotes: 1
Reputation: 132969
myceil.POSIXct <- function(x, digits=0) {
x1 <- as.numeric(x)
x1 <- ceiling(x1 * 10 ^ digits) / 10 ^ digits
attributes(x1) <- attributes(x)
x1
}
myceil.POSIXct(this_special_date, 3)
#[1] "2017-11-21 08:00:00.052 JST"
Upvotes: 2