我正在尝试将“2014年2月13日23:28:34”之类的字符串转换为日期。但是“as.Date”功能只产生了“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
答案 0 :(得分:3)
正如罗兰所说,这可能是一个地方问题。试试?strptime
的示例部分中的内容。
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"
答案 1 :(得分:0)
时间不是标准格式。这应该可以解决问题。我承认这是丑陋的代码。
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"
如果您的目的是转换为时间格式,这就是诀窍。如果你想转换成其他时间格式,那也可以。