R:如何从日期+时间字符串向量中获取日期向量?

时间:2015-02-20 05:33:22

标签: r

我有一个日期字符向量:

my.date.time.strings <- c("11/22/2014 15:48", "10/26/2014 10:44", "10/11/2014 20:18", "11/12/2014 13:58", "10/1/2014 20:59", "10/12/2014 11:13", "10/14/2014 15:54", "11/4/2014 8:36", "10/24/2014 17:22", "10/19/2014 16:51")

我想提取日期并将它们转换为R的日期类型。

我写了一个用sapply调用的函数:

getDate <- function(myDateTime) {
  ##This should get the date component of each string
  date = unlist(strsplit(as.character(myDateTime), " ", fixed = TRUE))[1]

  ##This should cast it
  date = as.Date(date, "%m/%d/%Y")

  return(date)
}

但是这个电话

print(my.dates <- sapply(my.date.time.strings, getDate))

返回我无法理解的结果:

[1] 16396 16369 16354 16386 16344 16355 16357 16378 16367 16362

我应该怎样做才能提取和格式化这些日期?

编辑:正如几位评论者(以及接受的答案)所说的那样简单,

my.dates <- as.Date(my.date.time.strings, "%m/%d/%Y")

1 个答案:

答案 0 :(得分:2)

您的功能有效,但它只是为您提供日期的数字表示。使用as.Date转换它并指定origin = "1970-01-01"

print(my.dates <- as.Date(sapply(
  my.date.time.strings, getDate), origin = "1970-01-01"))
# 11/22/2014 15:48 10/26/2014 10:44 10/11/2014 20:18 11/12/2014 13:58 
#     "2014-11-22"     "2014-10-26"     "2014-10-11"     "2014-11-12" 
#  10/1/2014 20:59 10/12/2014 11:13 10/14/2014 15:54   11/4/2014 8:36 
#     "2014-10-01"     "2014-10-12"     "2014-10-14"     "2014-11-04" 
# 10/24/2014 17:22 10/19/2014 16:51 
#     "2014-10-24"     "2014-10-19" 

当然,这是过度的,因为你可以直接使用as.Date

as.Date(my.date.time.strings, "%m/%d/%Y")
#  [1] "2014-11-22" "2014-10-26" "2014-10-11" "2014-11-12" "2014-10-01"
#  [6] "2014-10-12" "2014-10-14" "2014-11-04" "2014-10-24" "2014-10-19"