【问题标题】:extract specific hour from time stamp in given column从给定列中的时间戳中提取特定小时
【发布时间】:2019-11-29 17:32:16
【问题描述】:
timestamp
2001-06-12 14:05:00
2001-08-12 15:06:00
2001-09-11 18:05:00
2001-06-22 14:05:00
2001-06-02 14:05:00
2001-06-12 18:05:00
2001-06-12 14:05:00
2001-06-12 11:11:00
2001-06-12 18:59:00

我必须从上面的时间戳中找到18:00 hour(18:00:00 到 18:59:59)的频率。

输出应该如下所示:

Output      18th_hour      
Frequency   3

【问题讨论】:

    标签: r string datetime timestamp data-manipulation


    【解决方案1】:

    您可以提取时间戳的小时部分并计算"18"th 小时的出现次数。

    在基础 R 中,我们可以这样做

    sum(format(as.POSIXct(df$timestamp), "%H") == "18")
    #[1] 3
    

    类似使用lubridate

    library(lubridate)
    sum(hour(ymd_hms(df$timestamp)) == 18)
    

    数据

    df <- structure(list(timestamp = structure(c(3L, 7L, 8L, 6L, 1L, 4L, 3L, 2L, 
    5L), .Label = c("2001-06-02 14:05:00", "2001-06-12 11:11:00", 
    "2001-06-12 14:05:00", "2001-06-12 18:05:00", "2001-06-12 18:59:00", 
    "2001-06-22 14:05:00", "2001-08-12 15:06:00", "2001-09-11 18:05:00"
    ), class = "factor")), class = "data.frame", row.names = c(NA, -9L))
    

    【讨论】:

      【解决方案2】:

      带有anytime 的选项将“时间戳”列转换为日期时间,提取hour 并获取18 个元素的sum

      library(anytime)
      sum(hour(anytime(df$timestamp)) == 18)
      #[1] 3
      

      或者使用strptime 来自base R

      sum(strptime(df$timestamp, format = "%Y-%m-%d %H:%M:%S")$hour == 18)
      

      或者使用正则表达式选项

      sum(grepl(" 18", df$timestamp))
      #[1] 3
      

      数据

      df <- structure(list(timestamp = c("2001-06-12 14:05:00", "2001-08-12 15:06:00", 
      "2001-09-11 18:05:00", "2001-06-22 14:05:00", "2001-06-02 14:05:00", 
      "2001-06-12 18:05:00", "2001-06-12 14:05:00", "2001-06-12 11:11:00", 
      "2001-06-12 18:59:00")), class = "data.frame", row.names = c(NA, 
      -9L))
      

      【讨论】:

        猜你喜欢
        • 2015-11-20
        • 1970-01-01
        • 2013-05-08
        • 1970-01-01
        • 2015-03-30
        • 2017-01-15
        • 1970-01-01
        • 2021-12-09
        • 2020-07-07
        相关资源
        最近更新 更多