【问题标题】:Rounding time to the next milisecond将时间舍入到下一毫秒
【发布时间】:2018-02-22 12:56:05
【问题描述】:

考虑日期:

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

现在,我可以使用 this answer 中的函数 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 时间 下一个毫秒? - IE。在上述情况下,它将是 “2017-11-21 08:00:00.052”。

【问题讨论】:

    标签: r posixct posixlt


    【解决方案1】:
    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"
    

    【讨论】:

      【解决方案2】:

      您能否将 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)
      

      【讨论】:

      • 适用于该示例。但不适用于 '2017-11-20 23:00:00.097249000'
      • 当我尝试它时它会这样做:round(0.097249000 + 0.0005, digits = 3) 返回[1] 0.098。虽然当四舍五入到任何其他位数时它当然不起作用,但您还必须更改修饰符的小数位数。
      • 如果你在上面的例子中插入'2017-11-20 23:00:00.097249000'作为时间字符串并运行myformat.POSIXct(., digits=3)你得到"2017-11-21 08:00:00.097"
      • @user189035 请参阅上面的编辑以了解如何在您的代码中实现 0.0005(在 digits = 3 的情况下)的添加。这会在您的示例中给出"2017-11-21 08:00:00.098" 的输出。
      • 别担心,很高兴澄清它:)
      猜你喜欢
      • 1970-01-01
      • 2022-08-18
      • 2011-02-18
      • 2017-12-26
      • 2011-06-08
      • 2013-12-21
      • 1970-01-01
      • 1970-01-01
      • 2019-07-26
      相关资源
      最近更新 更多