首页 文章

24小时转换为POSIXct

提问于
浏览
0

我可以在大多数时候转换为POSIXct,例如:

as.POSIXct( "20:16:32", format = "%H:%M:%S" )
[1] "2017-06-23 20:16:32 EDT"

但是一旦时间超过24小时,就会失败:

as.POSIXct( "24:16:32", format = "%H:%M:%S" )
[1] NA

这有点意义,因为24:16:32应该读作00:16:32

然而,这种24标准在公共交通设计中得到了很好的发展 . 我当然可以用“00:”替换所有“24:”,但我相信有更优雅的出路 .

1 回答

  • 0

    将时间字符串读入数据帧dd,如果小时超过24或更多,则将next_day设置为1,否则设置为0 . 如果next_day为1,则从小时减去24,并添加1天的秒数 . 鉴于今天是2017年6月23日,这将在0到47之间工作几小时 .

    x <- "24:16:32" # test input
    
    dd <- read.table(text = x, sep = ":", col.names = c("hh", "mm", "ss"))
    next_day <- dd$hh >= 24
    s <- sprintf("%s %0d:%0d:%0d", Sys.Date(), dd$hh - 24 * next_day, dd$mm, dd$ss)
    as.POSIXct(s) + next_day * 24 * 60 * 60
    ##  "2017-06-24 00:16:32 EDT"
    

相关问题