Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

c
[1] "9/21/2011" "9/25/2011" "10/2/2011" "9/28/2011" "9/27/2011"
like image 998
David Z Avatar asked Apr 15 '14 16:04

David Z


People also ask

How do I remove the time from a date in CSV?

1. You can directly apply this formula =DATE(YEAR(A2),MONTH(A2),DAY(A2)) to remove time and only keep date from the date time format cell. 2.

How do I change character to time in R?

We can convert the character to timestamp by using strptime() method. strptime() function in R Language is used to parse the given representation of date and time with the given template.

How do I convert a character to a date in R?

You can use the as. Date( ) function to convert character data to dates. The format is as. Date(x, "format"), where x is the character data and format gives the appropriate format.


3 Answers

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:

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"
like image 91
digEmAll Avatar answered Oct 17 '22 17:10

digEmAll


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.

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)))
like image 25
Kayle Sawyer Avatar answered Oct 17 '22 19:10

Kayle Sawyer


Keeping original class as character. Use gsub (or sub) to remove everything after space. The .* pattern will find the first space.

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

gsub(" .*","", c)
[1] "9/21/2011" "9/25/2011" "10/2/2011" "9/28/2011" "9/27/2011"
like image 42
DAY Avatar answered Oct 17 '22 18:10

DAY