R将时间日期字符拆分为日期和时间

R将时间日期字符拆分为日期和时间,r,R,我有一个同时包含时间和日期的字符,我想将其拆分为日期和时间。 我试过: datetime格式应与初始向量中的格式相匹配 as.Date(datetime, "%H:%M:%S %d-%b-%Y") #[1] "2019-05-03" "2018-05-03" "2017-05-03" 如果要按空格进行拆分,请单击“” 或使用read.table df1 <- read.table(text = datetime, header = FALSE, col.names = c("time"

我有一个同时包含时间和日期的字符,我想将其拆分为日期和时间。 我试过:


datetime格式
应与初始向量中的格式相匹配

as.Date(datetime, "%H:%M:%S %d-%b-%Y")
#[1] "2019-05-03" "2018-05-03" "2017-05-03"

如果要按空格进行拆分,请单击“”

或使用
read.table

df1 <- read.table(text = datetime, header = FALSE, col.names = c("time", "date"))
df1$date <- as.Date(df1$date, "%d-%b-%Y")
df1
#       time       date
#1 12:00:00 2019-05-03
#2 02:01:00 2018-05-03
#3 11:00:22 2017-05-03
数据
datetime格式
应与初始向量中的格式相匹配

as.Date(datetime, "%H:%M:%S %d-%b-%Y")
#[1] "2019-05-03" "2018-05-03" "2017-05-03"

如果要按空格进行拆分,请单击“”

或使用
read.table

df1 <- read.table(text = datetime, header = FALSE, col.names = c("time", "date"))
df1$date <- as.Date(df1$date, "%d-%b-%Y")
df1
#       time       date
#1 12:00:00 2019-05-03
#2 02:01:00 2018-05-03
#3 11:00:22 2017-05-03
数据
datetime这里有一个函数,它将提取日期(作为
date
对象)和时间(作为字符串)。有关将时间保持为字符串的动机,请参见

extract_date_time <- function(dt){
  dt_split <- strsplit(dt, split=" ")
  lapply(dt_split, function(dts){
    list(date=as.Date(dts[2], '%d-%b-%Y'), time=dts[1])
  })
}

extract\u date\u time这里有一个函数,它将提取日期(作为
date
对象)和时间(作为字符串)。有关将时间保持为字符串的动机,请参见

extract_date_time <- function(dt){
  dt_split <- strsplit(dt, split=" ")
  lapply(dt_split, function(dts){
    list(date=as.Date(dts[2], '%d-%b-%Y'), time=dts[1])
  })
}
提取日期时间
extract_date_time <- function(dt){
  dt_split <- strsplit(dt, split=" ")
  lapply(dt_split, function(dts){
    list(date=as.Date(dts[2], '%d-%b-%Y'), time=dts[1])
  })
}
datetime <- as.character("12:00:00 03-May-2019")
extract_date_time(datetime)
datetimes <- c("12:00:00 03-May-2019",
               "02:01:00 03-May-2018",
               "11:00:22 03-May-2017")
extract_date_time(datetimes)