将字符向量转换为时间?

时间:2015-09-17 22:14:37

标签: r lubridate

我想将以下字符向量转换为时间变量。

times <-
  c(
    "9/9/2015 16:03:13", "9/9/2015 17:03:13", "9/9/2015 17:56:38",
    "9/9/2015 17:57:29", "9/9/2015 19:52:55", "9/10/2015 8:18:47",
    "9/9/2015 15:47:56", "9/9/2015 22:23:56", "9/10/2015 0:07:41",
    "9/10/2015 11:46:23", "9/11/2015 10:12:21", "9/11/2015 15:33:41",
    "9/12/2015 9:08:46", "9/15/2015 12:54:51", "9/15/2015 12:55:40",
    "9/15/2015 14:45:39", "9/15/2015 14:58:01", "9/15/2015 20:42:41",
    "9/16/2015 8:16:15", "9/16/2015 12:55:40", "9/16/2015 15:34:39",
    "9/17/2015 13:34:14", "9/17/2015 16:15:00"
  )

我尝试了以下内容:

fasttime::fastPOSIXct(format(times))

但我得到了很多NAs

structure(c(1425830593, 1425834193, 1425837398, 1425837449, 1425844375, 
           1428394727, 1425829676, 1425853436, 1428365261, 1428407183, 1431079941, 
           1431099221, 1433668126, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA
), class = c("POSIXct", "POSIXt"))    

1 个答案:

答案 0 :(得分:3)

这里有2个选项:

使用base-R:

as.POSIXct(times,format="%m/%d/%Y %H:%M:%S") ## this uses internally strptime

或使用方便的lubridate包:

library(lubridate)
parse_date_time(times,"mdYHMS")

library(lubridate)
mdy_hms(times)

fastPOSIXct是一个很好的选择,但我不认为它可以在这里使用(它假设数据具有某种格式)。