【问题标题】:Converting milliseconds to hh:mm format by considering the rounding in r通过考虑 r 中的舍入将毫秒转换为 hh:mm 格式
【发布时间】:2020-11-12 00:31:16
【问题描述】:

我正在尝试将毫秒转换为hh:mm 格式。我在下面尝试了这个:

x<-c(3159763, 2839300, 3821900)

t.adj <- 0
final <- strftime(as.POSIXlt.numeric(x/1000, format="%OS", origin="1970-01-01") - t.adj*3600,
                  format="%R", tz="GMT")

> final
[1] "00:52" "00:47" "01:03"

这里的问题是第一个元素的实际值是52 mins 38sec,所以由于它通过了​​一半,它应该是53 mins,就像00:53。第二个元素是47min 19sec,所以它可以保持为00:47,最后一个是1 H 3 Min 41 s,所以应该打印01:04

有没有人知道在这个函数中修复它或者可能有另一个解决这个舍入问题的方法?

谢谢!

【问题讨论】:

    标签: r time converters


    【解决方案1】:

    您可以使用lubridate 包中的round_date 在将毫秒转换为POSIXct 对象之后和使用strftime 格式化之前四舍五入到最接近的分钟数

    library(lubridate)
    
    x <- c(3159763, 2839300, 3821900)
    y <- as.POSIXct.numeric(x/1000, origin = '1970-01-01')
    z <- lubridate::round_date(y, unit = 'minute')
    
    strftime(z, format = '%R', tz='GMT')
    
    [1] "00:53" "00:47" "01:04"
    

    【讨论】:

      【解决方案2】:
      with(as.POSIXlt(x/1000, 'GMT', Sys.Date()),sprintf("%02d:%02d", hour,min+sec%/%30))
      
      [1] "00:53" "00:47" "01:04"
      

      编辑:

      你可以这样做:

       sprintf("%02d:%02d",(y<-round(x / 60000)) %/% 60, y %% 60)
      

      【讨论】:

      • 感谢您的回复。我遇到的一个警告是,当我们说59 mins 55secs 然后它四舍五入到00:60。相反,我们可以让它01:00 吗?
      猜你喜欢
      • 2018-03-25
      • 1970-01-01
      • 2022-11-28
      • 2012-02-20
      • 2014-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-02
      相关资源
      最近更新 更多