Search code examples
rdata-analysis

R: change timedate <chr> to separate date <date> and time<hms>


I have a date column that's output is in chr format:

glimpse(november$start_at): 
chr [1:337735] "01/11/2022 00:00" "01/11/2022 00:00" "01/11/2022 00:00" "01/11/2022 00:00" "01/11/2022 00:01" "01/11/2022 06:43"

I want to separate this into 2 separate date and time columns. the start_date should be in date format and the start time should be in time(hms) format. Note, the time in start_at only has hours and minutes no seconds, so I will just assume seconds as 00 for all data in november data frame. I want my output to like this:

start_date  start_Time 
2022/11/01  02:04:00
.
.
.  

so far I have done the date part:

november$start_date <- as.Date(format(as.Date(november$started_at, format = "%d/%m/%Y"), "%Y-%m-%d"))

str(november$start_date) 
 start_date     : Date[1:337735], format: "2022-11-01" "2022-11-01" "2022-11-01" "2022-11-01" 

the problem is that when I run the code for the time I get 00:00:00 for everything or NA for everything..

format(as.POSIXct(november$started_at), format = "%H:%M:%S")

 [1] "00:00:00" "00:00:00" "00:00:00" "00:00:00" "00:00:00" "00:00:00"

as.Date(parse_date_time(november$started_at,"dmy"))

 [1] NA NA NA NA NA NA NA NA NA 

thanks in advanced.

Solution

  • library(lubridate)
    library(tidyverse)
    
    november <- tibble(
      start_at = c(
        "01/11/2022 00:00",
        "01/11/2022 00:00",
        "01/11/2022 00:00",
        "01/11/2022 00:00",
        "01/11/2022 00:01",
        "01/11/2022 06:43"
      )
    )
    
    # A tibble: 6 × 1
      start_at        
      <chr>           
    1 01/11/2022 00:00
    2 01/11/2022 00:00
    3 01/11/2022 00:00
    4 01/11/2022 00:00
    5 01/11/2022 00:01
    6 01/11/2022 06:43
    

    Mutate new columns

    november %>% 
      mutate(
        start_date = as_date(mdy_hm(start_at)), 
        start_time = as_hms(mdy_hm(start_at))
      )
    
    # A tibble: 6 x 3
      start_at         start_date start_time
      <chr>            <date>     <time>    
    1 01/11/2022 00:00 2022-01-11 00:00     
    2 01/11/2022 00:00 2022-01-11 00:00     
    3 01/11/2022 00:00 2022-01-11 00:00     
    4 01/11/2022 00:00 2022-01-11 00:00     
    5 01/11/2022 00:01 2022-01-11 00:01     
    6 01/11/2022 06:43 2022-01-11 06:43