为什么我无法在 R 中将字符串"Feb 13 23:30:01 2014"转换为日期?



我正在尝试转换字符串,如"Feb 13 23:28:34 2014"到日期。但是"as"。"日期"功能只产生"NA"。我怎样才能做得正确?

head(time)
[1] "Feb 13 23:28:34 2014" "Feb 13 23:30:01 2014" "Feb 13 23:32:01 2014"
[4] "Feb 13 23:35:48 2014" "Feb 13 23:43:45 2014" "Feb 14 00:07:05 2014"
time <- as.Date(time, format = "%b %d %H:%M:%S %Y")
head(time)
[1] NA NA NA NA NA NA

正如Roland所建议的,这可能是一个地区问题。试试?strptime Example部分的内容。

R> lct <- Sys.getlocale("LC_TIME")  # store current time locale
R> Sys.setlocale("LC_TIME", "C")    # Use the "C" time locale
[1] "C"
R> x <- c("Feb 13 23:28:34 2014","Feb 13 23:30:01 2014","Feb 13 23:32:01 2014",
+        "Feb 13 23:35:48 2014","Feb 13 23:43:45 2014","Feb 14 00:07:05 2014")
R> # If you want a Date object (no time)
R> (d <- as.Date(x, format = "%b %d %H:%M:%S %Y"))
[1] "2014-02-13" "2014-02-13" "2014-02-13" "2014-02-13" "2014-02-13"
[6] "2014-02-14"
R> # If you want a POSIXt (date/time) object
R> (p <- as.POSIXct(x, format = "%b %d %H:%M:%S %Y"))
[1] "2014-02-13 23:28:34 CST" "2014-02-13 23:30:01 CST"
[3] "2014-02-13 23:32:01 CST" "2014-02-13 23:35:48 CST"
[5] "2014-02-13 23:43:45 CST" "2014-02-14 00:07:05 CST"
R> Sys.setlocale("LC_TIME", lct)  # restore original time locale
[1] "en_US.UTF-8"

时间不符合标准格式。这应该能奏效。我承认这是一段丑陋的代码。

library(lubridate)
library(stringr)
time  <- c("Feb 13 23:28:34 2014","Feb 13 23:30:01 2014","Feb 13 23:32:01 2014","Feb 13 23:35:48 2014","Feb 13 23:43:45 2014","Feb 14 00:07:05 2014")
year <- substr(time,start = 17,stop = 20)
time <- gsub(pattern = substr(time,start = 16,stop = 20),replacement = "",x = time)
time <- paste(year,time,sep = " ")
time  <- ymd_hms(time)
time
[1] "2014-02-13 23:28:34 UTC" "2014-02-13 23:30:01 UTC"
[3] "2014-02-13 23:32:01 UTC" "2014-02-13 23:35:48 UTC"
[5] "2014-02-13 23:43:45 UTC" "2014-02-14 00:07:05 UTC"
 time <- as.Date(time, format = "%b %d %H:%M:%S %Y")
 time
[1] "2014-02-13" "2014-02-13" "2014-02-13" "2014-02-13" "2014-02-13"
[6] "2014-02-14"

如果你的目的是转换成时间格式,这是技巧。如果你想转换成其他时间格式,也可以。

最新更新