【问题标题】:Convert decimal hours to HH:MM:SS将十进制小时转换为 HH:MM:SS
【发布时间】:2013-11-12 07:44:07
【问题描述】:

我正在寻找一种将十进制小时数转换为 HH:MM:SS

的方法

例如,作为输入:

4.927778 hours

期望的输出:

04:55:40

【问题讨论】:

    标签: r time format decimal


    【解决方案1】:

    当您将小时数、分钟数和秒数设为整数时,您可以使用sprintf() 来格式化输出。这些可以使用模数 (%%) 和 floor()/round() 来计算。使用 readr 包中的 parse_number() 函数可以很好地从字符串中提取小时数:

    library(readr) 
    input <- "4.927778 hours"
    hrs <- parse_number(input)
    hours <- floor(hrs)
    minutes <- floor((hrs %% 1) * 60)
    seconds <- round((((hrs %% 1) * 60) %% 1) * 60)
    
    sprintf("%02d:%02d:%02d", hours, minutes, seconds)
    

    与使用strftime() 的解决方案相比,此策略的优势在于它仍然适用于大于 24 小时的时差。

    【讨论】:

      【解决方案2】:

      这也适用于负值。

      convertHours<-function(hours){ timeoffset<-as.numeric(as.POSIXct(format(Sys.time(), tz = "GMT")) - as.POSIXct(format(Sys.time(), tz = ""))) hoursMinutes<-ifelse(hours<0,paste0("-",strftime(as.POSIXct((abs(hours)+timeoffset) * 60 * 60, origin = Sys.Date(), tz =""), format = "%H:%M")), strftime(as.POSIXct((hours+timeoffset) * 60 * 60, origin = Sys.Date(), tz =""), format = "%H:%M")) }

      h

      hhmm

      hhmm [1] "01:19"

      h

      hhmm

      hhmm [1] "-01:19"

      【讨论】:

        【解决方案3】:

        你可以试试下面的方法

        dh <- 4.927778
        strftime(as.POSIXct(dh * 60 * 60, origin = Sys.Date(), tz = "GMT"), format = "%H:%M:%S")
        ## [1] "04:55:40"
        

        【讨论】:

        • 值得指出的是,这仅适用于
        【解决方案4】:

        另一种解决方案是将其转换为日期/时间类,然后以适当的方式对其进行格式化。

        format(ISOdatetime(1900,1,1,0,0,0, tz="GMT") + 
               as.difftime(4.927778, unit="hours"), "%H:%M:%S")
        

        【讨论】:

          【解决方案5】:

          你应该能够了解你需要做什么 -

          a <- "4.927778 hours"
          a <- as.numeric(gsub(x = a,pattern = " hours", replacement = ""))
          
          h <- a%/% 1
          m <- ((a%% 1)*60) %/% 1
          s <- round((((a%% 1)*60) %% 1)*60,0)
          paste(h,m,s,sep = ":")
          #[1] "4:55:40"
          

          【讨论】:

            【解决方案6】:

            如果您使用的是 .net/C#,则可以使用一点日期数学。

            var when = DateTime.UtcNow; // or any time of your choice
            var later = when.AddHours(4.927778);
            var span = later - when;
            Console.WriteLine(span)
            

            我现在看到了 R 标志。也许这会给你一个提示,在哪里寻找类似的东西。我不知道R。

            【讨论】:

            • 语言是R(每当我看到示例代码时,我都会感到有些困惑)。
            猜你喜欢
            • 2016-05-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-12-12
            相关资源
            最近更新 更多