通过考虑 r 中的舍入将毫秒转换为 hh:mm 格式

Converting milliseconds to hh:mm format by considering the rounding in r

我正在尝试将毫秒转换为 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 mins00:53。第二个元素是 47min 19sec 所以它可以保持 00:47 最后一个是 1 H 3 Min 41 s 所以它应该打印 01:04.

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

谢谢!

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)

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

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"