【问题标题】:Convert time shown as hours and minutes in three to four digits within a dataframe to minutes将数据帧内以三到四位数显示为小时和分钟的时间转换为分钟
【发布时间】:2019-06-20 03:44:49
【问题描述】:

我有一个数据框,其中有一列名为“时间”(它有一个整数类)。时间以三位数或四位数表示,例如514,表示上午 5:14,或 1914,表示 19:14。我需要创建一个新列“time_2”,其中包含“时间”列的时间,但只显示分钟。例如,如果第 1 行的“时间”列的值为“514”,则需要转到名为“time_2”的新列,第一个值为“314”分钟。

我试图“删除”第一个数字,然后将其乘以 60,然后将其后的两位数相加。但是,我无法完成它,而且还有四位数的数据这一事实让我停下来寻求帮助。我只是不知道该怎么做。我真的很感激一些帮助。

(语言:R)

【问题讨论】:

    标签: r dataframe time


    【解决方案1】:

    如果您的时间从未超出 00:00-23:59 窗口,您可以使用 base R 中的as.difftime

    x <- c(514,1914)
    
    as.difftime(sprintf("%04d", x), format="%H%M", units="mins")
    #Time differences in mins
    #[1]  314 1154
    

    这个范围之外的时间可以用一点算术来处理:

    as.numeric(
      as.difftime(x %/% 100 + (x %% 100)/60, units="hours"),
      units="mins"
    )
    #[1]  314 1154
    

    【讨论】:

      【解决方案2】:

      将数字转换为 timestamp 并使用 substr 提取小时和分钟

      library("lubridate")
      
      InPut
      time <- c(521,1914)
      time <- substr(as.POSIXct(sprintf("%04.0f", time), format='%H%M'), 12, 16) # Extracting hours and minutes using substr
      time <- as.POSIXct(x = time, format = "%H:%M", tz = "UTC")
      hour(time) * 60 + minute(time)
      
      OutPut:
      [1]  321 1154
      

      【讨论】:

        【解决方案3】:

        以更简单的方式:

        library(lubridate)
        time <- c(521,1914)
        60 *hour(parse_date_time(time, "HM"))+ minute(parse_date_time(time, "HM"))
        

        【讨论】:

          猜你喜欢
          • 2019-02-22
          • 2015-07-20
          • 1970-01-01
          • 2012-01-23
          • 1970-01-01
          • 2015-05-18
          • 1970-01-01
          • 1970-01-01
          • 2020-03-23
          相关资源
          最近更新 更多