将char转换为日期时间

时间:2012-10-12 17:01:31

标签: r

在data.frame中,我有一个日期时间戳:

head(x$time)
[1] "Thu Oct 11 22:18:02 2012" "Thu Oct 11 22:50:15 2012" "Thu Oct 11 22:54:17 2012"
[4] "Thu Oct 11 22:43:13 2012" "Thu Oct 11 22:41:18 2012" "Thu Oct 11 22:15:19 2012"

每当我尝试使用as.Date lubridate 动物园转换它时,我会得到NA或错误。

将此时间转换为可读形式的方式是什么?

我试过了:

 Time<-strptime(x$time,format="&m/%d/%Y  %H:$M")
    x$minute<-parse_date_time(x$time)
    x$minute<-mdy(x$time)
    x$minute<-as.Date(x$time,"%m/%d/%Y %H:%M:%S")
    x$minute<-as.time(x$time)
    x$minute<-as.POSIXct(x$time,format="%H:%M")
    x$minute<-minute(x$time)

2 个答案:

答案 0 :(得分:18)

你真正想要的是strptime()。尝试类似:

strptime(x$time, "%a %b %d %H:%M:%S %Y")

作为您可以使用strptime()执行的有趣事项的示例,请考虑以下事项:

thedate <- "I came to your house at 11:45 on January 21, 2012."
strptime(thedate, "I came to your house at %H:%M on %B %d, %Y.")
# [1] "2012-01-21 11:45:00"

答案 1 :(得分:0)

另一种选择是使用lubridate::parse_date_time()

library(lubridate)
parse_date_time(x$time, "%a %b %d %H:%M:%S %Y")

或更简单地说:

parse_date_time(x$time, "abdHMSY")

从文档中

  

它在两个方面与base :: strptime()不同。首先,它允许指定格式出现的顺序,而无需包括分隔符和%前缀。这种格式化参数称为“顺序”。其次,它允许用户指定几种格式顺序来处理不同的日期时间字符表示形式。

文档包含lubridate可以识别的所有格式(“ abdHMSY”等)。