【问题标题】:How do I convert numeric value into hours and minutes depending upon the number of digits如何根据位数将数值转换为小时和分钟
【发布时间】:2019-07-09 10:20:11
【问题描述】:

我有一个向量,其中包含最近半小时的时间

x <- c(30,200,2200,2300)

我需要把它转换成

output <- c(00:30,02:00,22:00,23:00).

我无法转换小于 4 位的值。
请建议。 strptime() , as.Date() 为第一个元素抛出 NA

我尝试了以下代码,但没有成功。请推荐

代码:

x <- c(30,200,2200,2300)

output <- format(strptime(x,"%H%M"),"%H:%M")
output
#[1] NA      "20:00" "22:00" "23:00"

【问题讨论】:

    标签: r datetime-conversion


    【解决方案1】:

    您可以使用sprintf,添加前导零。

    x <- c(30, 200, 2200, 2300)
    format(strptime(sprintf("%04d", x), format="%H%M"), format="%H:%M")
    # [1] "00:30" "02:00" "22:00" "23:00"
    

    【讨论】:

    • @R06 不客气!考虑选择一个答案和mark an answer as accepted。这就是我们在 Stack Overflow 上说 thank you 的方式。从您拥有 +15 声望的那一刻起,您也可以upvote an answer
    【解决方案2】:

    使用formatC的另一种方式

    x <- c(30, 200, 2200, 2300)
    formatC(x, width = 4, flag = "0", big.mark = ":", big.interval = 2)
    #[1] "00:30" "02:00" "22:00" "23:00"
    

    【讨论】:

      【解决方案3】:

      如果你想得到一个字符串,你可以用一些正则表达式绕过strptime()

      sub("(\\d{2})", "\\1:", sprintf("%04d", x))
      [1] "00:30" "02:00" "22:00" "23:00"
      

      【讨论】:

        【解决方案4】:

        似乎x中的字符数需要调整为格式字符串"%H%M"至少3个字符才能理解所有情况下都有一个小时。

        tmp <- strptime(ifelse(nchar(x) <= 3, paste("0", x), x),"%H%M")
        output <- format(tmp,"%H:%M")
        output
        #[1] "00:30" "02:00" "22:00" "23:00"
        

        【讨论】:

        • 当前与预期输出不匹配。
        猜你喜欢
        • 1970-01-01
        • 2020-06-16
        • 2019-02-22
        • 1970-01-01
        • 2021-09-19
        • 1970-01-01
        • 2012-01-23
        • 1970-01-01
        • 2015-07-20
        相关资源
        最近更新 更多