拆分字符串以提取日期和时间 [英] Splitting Character String to Extract Date and Time

查看:318
本文介绍了拆分字符串以提取日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在小标题的列中有一个字符串,看起来像Nov 01, 2019 8:00:41 AM CDT.

I have a character string in a column of a tibble that looks like Nov 01, 2019 8:00:41 AM CDT.

我想在提到的列日期和时间"中创建新列.

I would like to create new columns of the mentioned column, Date and Time.

执行此操作的最佳方法是什么?润滑吗?

What is the best approaches into doing this? Lubridate?

Time <- tibble(Call = 1, Date_Time = 'Nov 01, 2019 8:00:41 AM CDT')
Time %>%
    mutate(Date_Time = mdy(`Contact Start Date/Time`))

我尝试了上面的代码,但是,我的新专栏什么都没有,只有"NA".

I tried the code above but, my new column had nothing, but "NAs" in them.

推荐答案

1)如图所示,我们可以使用as.POSIXctas.Date.我不确定您想要的时间,但是在下面提供了一个字符串时间.

1) We can use as.POSIXct and as.Date as shown. I am not sure what you want for the time but have provided a character string time below.

library(dplyr)

DF %>% mutate(x = as.POSIXct(x, format = "%b %d, %Y %I:%M:%S %p"),
         date = as.Date(x),
         time = sub(".* ", "", x))
##                     x       date     time
## 1 2019-11-01 08:00:41 2019-11-01 08:00:41

2):chron程序包可以分别表示日期和时间:

2) The chron package can represent dates and times separately:

library(dplyr)
library(chron)

DF %>% 
  mutate(x = as.chron(as.character(x), format = "%b %d, %Y %I:%M:%S %p"),
         date = dates(x),
         time = x - date)

##                     x     date     time
## 1 (11/01/19 08:00:41) 11/01/19 08:00:41

注意

DF <- data.frame(x = "Nov 01, 2019 8:00:41 AM CDT")

这篇关于拆分字符串以提取日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆