简体   繁体   English

删除向量中前 10 个字符之后的所有字符 (R)

[英]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.我是 R 的新手,我希望从 Salesforce 数据的date/time字段中删除时间戳。 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.这些日期采用以下格式"2019-09-06T07:44:59.9999997904524" ,我需要删除包括 T 之后的所有内容,然后转换为mm/dd/yyyy格式。 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 anytimeanytime使用

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

or in base R或在base R

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

data数据

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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