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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23089895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:16:10  来源:igfitidea点击:

How to remove time-field string from a date-as-character variable?

stringrsubstringdate-formatting

提问by David Z

Suppose I have a variable like this

假设我有一个这样的变量

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")

what's a quick way to remove all 0:00:00s so that

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

c
[1] "9/21/2011" "9/25/2011" "10/2/2011" "9/28/2011" "9/27/2011"

回答by digEmAll

You can turn them into dates and then format as desired, e.g.:

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

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"

Or, you can simply remove the " 0:00:00"substring using gsub:

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

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"

回答by Kayle Sawyer

From the lubridate package: Use mdy_hms()to read in the characters as Month, Day, Year and Hours, Minutes, Seconds, then wrap with as.Date()to strip the time.

从 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"

If you want to maintain the vector as character type, not date type:

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

v <- as.character(as.Date(mdy_hms(v)))