newbe
newbe

Reputation: 15

How to separate date and time from datetime format using R

I have a dataset called "Tickets" where there is a column called Date Created. I want to separate date and time and form a new column called Date and Time (That means I want to mutate).

enter image description here.

I tried using lubridate but it gives me NA values.

Also I used :

Hours <- format(as.POSIXct(strptime(tickets$`Date Created`,"%m/%d/%Y %H:%M",tz="")) ,format = "%H:%M")
Hours

However if I am trying to view the dataset it doesn't show any column named Hours Please can anybody tell me whats the issue.

Thank you very much.

Edit : I was finally able to separate them using below code tickets %>% mutate_at(vars(Date Created), mdy_hms) %>% mutate_at(vars(Date Created), funs("date" = date(.), "time" = as.hms(.))) %>% select(-Date Created) However it shows wrong date and timeenter image description here

What can be wrong with this code?

Upvotes: 0

Views: 5114

Answers (2)

AndS.
AndS.

Reputation: 8120

Try this out. I only use three dates as an example. First we change your character class to a date time, then we extract out the dates, lastly we extract the times. I assume you want the date as class date and the time as class time. If not, the other solution would be easier. Also note that I add seconds to the time for ease of use.

library(tidyverse)
library(lubridate)

df <- data_frame(date_time = c("8/1/2018 4:55", "8/1/2018 7:53", "8/1/2018 10:10"))
df %>%
  mutate(date_time = paste0(date_time, ":00"),
         date_time = parse_date_time(date_time, orders = "mdy HMS"),
         date = date(date_time), 
         time = chron::times(strftime(date_time,"%H:%M:%S", tz = "UTC")))
#> # A tibble: 3 x 3
#>   date_time           date       time       
#>   <dttm>              <date>     <S3: times>
#> 1 2018-08-01 04:55:00 2018-08-01 04:55:00   
#> 2 2018-08-01 07:53:00 2018-08-01 07:53:00   
#> 3 2018-08-01 10:10:00 2018-08-01 10:10:00

Upvotes: 2

Matheus Deister Veiga
Matheus Deister Veiga

Reputation: 36

From what I can tell by your question:

library(tidyverse)
head(df)
testTime
1 2018-11-24 02:44:07
new_df <- separate(data = df, col = testTime, into  = c('Date', 'Time'), sep = ' ')
head(new_df)
  Date     Time
1 2018-11-24 02:44:07

Should get you there.

Consider rewording the last part of your question, I could not understand what you are asking. Also, use typeof() in your column, dates can be stored either as strings or integers and look the same.

Upvotes: 2

Related Questions