【问题标题】:How can I convert number to hh:mm:ss?如何将数字转换为 hh:mm:ss?
【发布时间】:2022-02-04 12:23:15
【问题描述】:

我在数据框中有一列是午夜过后的秒数。我将如何将该数字转换为显示为 hh:mm:ss 的时间?例如:

hrsecs
1563
13088
14309

变成

Time
00:26:03
03:38:08
03:58:29

【问题讨论】:

    标签: r time


    【解决方案1】:

    将秒数转换为句点 (seconds_to_period) 并使用 hms 包中的 hms

    library(lubridate)
    library(dplyr)
    df1 <- df1 %>% 
       transmute(Time = hms::hms(seconds_to_period(hrsecs)))
    

    -输出

    df1
      Time
    1 00:26:03
    2 03:38:08
    3 03:58:29
    

    数据

    df1 <- structure(list(hrsecs = c(1563L, 13088L, 14309L)), 
    class = "data.frame", row.names = c(NA, 
    -3L))
    

    【讨论】:

      【解决方案2】:

      1) 字符输出 转换成POSIXct再格式化。没有使用任何包。

      x <- c(1563, 13088, 14309)
      tt <- format(as.POSIXct("1970-01-01") + x, "%T"); tt
      ## [1] "00:26:03" "03:38:08" "03:58:29"
      

      tt <- format(structure(x, class = c("POSIXct", "POSIXt"), tzone = "UTC"), "%T")
      tt
      ## [1] "00:26:03" "03:38:08" "03:58:29"
      

      2) 时间类输出如果您希望能够操纵时间,那么这将在内部将它们表示为一天的分数,但将它们呈现为时间。

      library(chron)
      times(tt)
      ## [1] 00:26:03 03:38:08 03:58:29
      

      【讨论】:

        猜你喜欢
        • 2015-05-27
        • 1970-01-01
        • 1970-01-01
        • 2011-02-23
        • 2013-10-12
        • 2014-09-18
        • 1970-01-01
        • 2019-08-07
        • 1970-01-01
        相关资源
        最近更新 更多