Splitting Character String to Extract Date and Time [duplicate]

∥☆過路亽.° 提交于 2020-03-04 18:57:10

问题


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`))

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


回答1:


We can use lubridates mdy_hms function to convert Date_Time to POSIXct format and then extract Date and Time using as.Date and format respectively.

library(dplyr)
library(lubridate)

Time %>%
  mutate(Date_Time = mdy_hms(Date_Time), 
         Date = as.Date(Date_Time), 
         Time = format(Date_Time, "%T"))

#   Call Date_Time           Date       Time    
#  <dbl> <dttm>              <date>     <chr>   
#1     1 2019-11-01 08:00:41 2019-11-01 08:00:41



回答2:


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) 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

Note

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


来源:https://stackoverflow.com/questions/60227193/splitting-character-string-to-extract-date-and-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!