代码之家  ›  专栏  ›  技术社区  ›  SeGa

以毫秒为单位计算时间差

  •  1
  • SeGa  · 技术社区  · 7 年前

    我想用毫秒计算时间戳的差。区别( 时间差异 )在下面的示例中 应始终为0.2 ,但我也得到了高于和低于0.2的值。

    问题开始了,当 划分 毫秒到秒和/或相加 numeric 值到A POSIXct 对象。

    我假设这是一个浮点问题,所以我尝试指定 digits.sec和digits,舍入,截断, 等。。。但问题依然存在。

    这到底是为什么以及如何解决这个问题?

    library(dplyr)
    
    options("digits.secs"=10)
    options(digits = 10)
    
    id <- 1:12
    time <- c("9:34:50" , "9:34:50" , "9:34:51" , "9:34:51" , "9:34:51" , "9:34:51" ,
      "9:34:51" , "9:34:52" , "9:34:52" , "9:34:52" , "9:34:52" , "9:34:52")
    ms <- c(600,800,0,200,400,600,800,0,200,400,600,800)
    
    time <- as.POSIXct(time, format="%H:%M:%S", tz="GMT")
    
    # Problem begins here
    timeNew <- time + (ms/1000)
    
    timeNewDf <- data.frame(id=id,
                          time=timeNew)
    
    timeNewDf %>% dplyr::mutate(
      time_diff = c(diff(time),0)) %>% 
      dplyr::rowwise()
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Mankind_2000    7 年前

    posixct将接近其最近的浮点,而不是精确的时间。添加偏移量以适应浮点近似值,并显示到1位毫秒。

    library(dplyr) 
    options("digits.secs"=1)                                        # showing upto 1 digit
    
    # test data
    id <- 1:12
    time <- c("9:34:50" , "9:34:50" , "9:34:51" , "9:34:51" , "9:34:51" , 
              "9:34:51" , "9:34:51" , "9:34:52" , "9:34:52" , "9:34:52" , "9:34:52" , "9:34:52")
    ms <- c(600,800,0,200,400,600,800,0,200,400,600,800)
    time <- as.POSIXct(time, format="%H:%M:%S", tz="GMT")
    
    # offset to cater to floating point approximations
    timeNew <- time + (ms/1000) + .0001
    
    timeNewDf <- data.frame(id=id, time=timeNew)
    timeNewDf %>% mutate(time_diff = round(c(diff(time),0),1))      # rounding to 1 decimal digit
    
    #1   1 2018-05-30 09:34:50.6  0.2 secs
    #2   2 2018-05-30 09:34:50.8  0.2 secs
    #3   3 2018-05-30 09:34:51.0  0.2 secs
    #4   4 2018-05-30 09:34:51.2  0.2 secs
    #5   5 2018-05-30 09:34:51.4  0.2 secs
    #6   6 2018-05-30 09:34:51.6  0.2 secs
    #7   7 2018-05-30 09:34:51.8  0.2 secs
    #8   8 2018-05-30 09:34:52.0  0.2 secs
    #9   9 2018-05-30 09:34:52.2  0.2 secs
    #10 10 2018-05-30 09:34:52.4  0.2 secs
    #11 11 2018-05-30 09:34:52.6  0.2 secs
    #12 12 2018-05-30 09:34:52.8  0.0 secs