【问题标题】:Remove seconds from time in R从 R 中的时间中删除秒数
【发布时间】:2016-09-28 19:58:50
【问题描述】:

我正在尝试从 POSIXct 格式的小时列中删除秒数:

#"2016-04-02 10:33:45 COT" "2016-04-02 22:19:24 COT"
#"2016-04-09 17:47:13 COT" "2016-04-13 16:56:23 COT"

x <- structure(c(1459589625, 1459631964, 1460220433, 1460562983),
     class = c("POSIXct", "POSIXt"), tzone = "")

我正在尝试这个,但我没有看到结果:

y <- as.POSIXct(x, format = "%d/%m/%Y %H:%M")

【问题讨论】:

    标签: r posixct


    【解决方案1】:

    不,你给as.POSIXct 一个错误的格式...

    如何使用格式

    datetimes = as.POSIXct(c("2016-04-02 10:33:45 COT", "2016-04-02 22:19:24 COT" ,"2016-04-09 17:47:13 COT", "2016-04-13 16:56:23 COT")    
    format(datetimes,format='%Y%m%d %H:%M')
    
    [1] "20160402 10:33" "20160402 22:19" "20160409 17:47" "20160413 16:56"
    

    【讨论】:

    • 第一行似乎缺少右括号。没什么大不了的,还是很有帮助的!
    【解决方案2】:

    你可以使用round.POSIXt:

    round(Sys.time(), units = "mins")
    #"2017-01-30 11:20:00 CET"
    

    【讨论】:

    • 如果你使用这个函数来操作一个data.frame你需要一个额外的as.POSIXct来移除列表结构
    【解决方案3】:

    这就是你所拥有的:

    x <- structure(c(1459589625, 1459631964, 1460220433, 1460562983),
         class = c("POSIXct", "POSIXt"), tzone = "")
    

    这就是你想要的:

    x <- format(as.POSIXct(x), "%d-%m-%Y %H:%M")
    x
    
    [1] "02-04-2016 15:03" "03-04-2016 02:49" "09-04-2016 22:17" "13-04-2016 21:26"
    

    【讨论】:

      【解决方案4】:

      如果您想将日期四舍五入到分钟,您可以这样做:

         x <- as.POSIXlt(c("2016-04-02 10:33:45 COT"))
         res <-as.POSIXlt(floor(as.double(x) / 60) * 60, origin = '1970-01-01')
         res
         #  "2016-04-02 10:33:00 BST"
      

      【讨论】:

      • 请参阅%/% 以简化表达式。
      【解决方案5】:

      只需使用子字符串:

      datetimes <- c("2016-04-02 10:33:45 COT", "2016-04-02 22:19:24 COT" ,
                     "2016-04-09 17:47:13 COT", "2016-04-13 16:56:23 COT")
      
      as.POSIXct(substring(datetimes, 1, nchar(datetimes[1])-7))   
      
      #[1] "2016-04-02 10:33:00 IST" "2016-04-02 22:19:00 IST" 
      #    "2016-04-09 17:47:00 IST" "2016-04-13 16:56:00 IST"
      
      # without timezone
      format(substring(datetimes, 1, nchar(datetimes[1])-7), 
                       format='%Y-%m-%d %H:%M:%S', usetz = FALSE)
      #[1] "2016-04-02 10:33" "2016-04-02 22:19" "2016-04-09 17:47" "2016-04-13 16:56"
      

      【讨论】:

      • 此处显示的时区字符串不会导致置信度。
      猜你喜欢
      • 2015-10-13
      • 2016-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-06
      相关资源
      最近更新 更多