简体   繁体   中英

Removing all characters after the first 10 characters in a vector (R)

I'm a rookie with R and am looking to remove the timestamp from a date/time field from Salesforce data. These dates are in the following format "2019-09-06T07:44:59.9999997904524" and I need to remove everything after and including the T, then convert to mm/dd/yyyy format. How would I accomplish this?

It would probably be better to parse the date and format as desired

format(as.Date("2019-09-06T07:44:59.9999997904524"), "%m/%d/%Y")
#OR
format(lubridate::ymd_hms( "2019-09-06T07:44:59.9999997904524"), "%m/%d/%Y")
#[1] "09/06/2019"

If we need a regex solution, capture as a group and then rearrange the backreferences

sub("(.{4})-(.{2})-(.{2}).*", "\\2/\\3/\\1", v1)
#[1] "09/06/2019"

Or using anytime

library(anytime)
format(anytime(v1), "%m/%d/%Y")
#[1] "09/06/2019"

or in base R

format(as.Date(v1), "%m/%d/%Y")

data

v1 <- "2019-09-06T07:44:59.9999997904524"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM