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

后端 未结 2 1310
深忆病人
深忆病人 2020-12-15 20:01

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         


        
相关标签:
2条回答
  • 2020-12-15 20:46

    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"
    
    0 讨论(0)
  • 2020-12-15 20:55

    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)))
    
    0 讨论(0)
提交回复
热议问题