如何从日期为字符的变量中删除时间字符串?

问题描述 投票:11回答:2

假设我有一个像这样的变量

c<-c("9/21/2011 0:00:00",  "9/25/2011 0:00:00",  "10/2/2011 0:00:00",  
"9/28/2011 0:00:00",  "9/27/2011 0:00:00")

什么是快速删除所有0:00:00s的方法

c
[1] "9/21/2011" "9/25/2011" "10/2/2011" "9/28/2011" "9/27/2011"
string r substring date-formatting
2个回答
16
投票

您可以将它们转换为日期,然后根据需要进行格式化,例如:

v <- c("9/21/2011 0:00:00",  "9/25/2011 0:00:00",  "10/2/2011 0:00:00",  
     "9/28/2011 0:00:00",  "9/27/2011 0:00:00")
v <- format(as.POSIXct(v,format='%m/%d/%Y %H:%M:%S'),format='%m/%d/%Y')
> v
[1] "09/21/2011" "09/25/2011" "10/02/2011" "09/28/2011" "09/27/2011"

或者,您可以使用gsub删除" 0:00:00"子字符串:

v <- gsub(x=v,pattern=" 0:00:00",replacement="",fixed=T)
> v
[1] "9/21/2011" "9/25/2011" "10/2/2011" "9/28/2011" "9/27/2011"

3
投票

从lubridate包中:使用mdy_hms()读取字符为月,日,年和小时,分钟,秒,然后用as.Date()换行以消除时间。

library(lubridate)
v <- c("9/21/2011 0:00:00",  "9/25/2011 0:00:00",  "10/2/2011 0:00:00",  
       "9/28/2011 0:00:00",  "9/27/2011 0:00:00")
v <- as.Date(mdy_hms(v))
v
# [1] "2011-09-21" "2011-09-25" "2011-10-02" "2011-09-28" "2011-09-27"

如果要将向量维护为字符类型,而不是日期类型:

v <- as.character(as.Date(mdy_hms(v)))
© www.soinside.com 2019 - 2024. All rights reserved.