0

考虑日期:

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')

现在,我可以使用此答案中的函数myformat.POSIXct舍入到最接近的毫秒:

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)

返回:“2017-11-21 08:00:00.051”。但是如何将 POSIXct 时间舍入到下一个毫秒?--即在上述情况下,它将是“2017-11-21 08:00:00.052”。

4

2 回答 2

2
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"
于 2018-02-22T13:02:33.577 回答
1

您可以将 00.0005 添加到所有值吗?这将确保它们始终相对于起始值进行四舍五入。

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)
于 2018-02-22T12:59:47.570 回答