Search code examples
rtidyverselubridate

How to merge date and time into one variable


I want to have a date variable and a time variable as one variable like this 2012-05-02 07:30

This code does the job, but I need to get a new combined variable into the data frame, and this code shows it only in the console as.POSIXct(paste(data$Date, data$Time), format="%Y-%m-%d %H:%M")

This code is supposed to combine time and date, but seemingly doesn't do that. In the column "Combined" only the date appears data$Combined = as.POSIXct(paste0(data$Date,data$Time))

Here's the data

structure(list(Date = structure(c(17341, 18198, 17207, 17023, 
17508, 17406, 18157, 17931, 17936, 18344), class = "Date"), Time = c("08:40", 
"10:00", "22:10", "18:00", "08:00", "04:30", "20:00", "15:40", 
"11:00", "07:00")), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"))

Solution

  • We could use ymd_hm function from lubridate package:

    library(lubridate)
    
    df$Date_time <- ymd_hm(paste0(df$Date, df$Time))
    
       Date       Time  Date_time          
       <date>     <chr> <dttm>             
     1 2017-06-24 08:40 2017-06-24 08:40:00
     2 2019-10-29 10:00 2019-10-29 10:00:00
     3 2017-02-10 22:10 2017-02-10 22:10:00
     4 2016-08-10 18:00 2016-08-10 18:00:00
     5 2017-12-08 08:00 2017-12-08 08:00:00
     6 2017-08-28 04:30 2017-08-28 04:30:00
     7 2019-09-18 20:00 2019-09-18 20:00:00
     8 2019-02-04 15:40 2019-02-04 15:40:00
     9 2019-02-09 11:00 2019-02-09 11:00:00
    10 2020-03-23 07:00 2020-03-23 07:00:00