问题
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 lubridate
s 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