Want to combine date and time in a column using R
Asked Answered
R

3

8

I have the following dataframe

 Date             Time
10/03/2014       12.00.00
11/03/2014       13.00.00
12/03/2014       14.00.00

I want to create one single column as follows

DT
10/03/2014 12.00.00
11/03/2014 13.00.00
12/03/2014 14.00.00

when I run

data$DT <- as.POSIXct(paste(x$Date, x$Time), format="%d-%m-%Y %H:%M:%S")

I get a column DT with all NA values.

Rodriques answered 17/7, 2018 at 13:21 Comment(2)
change your format from "%d-%m-%Y %H:%M:%S" to "%d/%m/%Y %H.%M.%S"Elyse
Thanks. It workedRodriques
H
6
Data$DT <- as.POSIXct(as.character(paste(data$Date, data$Time)), format="%d/%m/%Y %H.%M.%S")

OR

data$Time <- gsub('\\.',':',data$Time)
data$Date <- gsub('/','-',data$Date)

data$DT <- as.POSIXct(as.character(paste(data$Date, data$Time)), format="%d-%m-%Y %H:%M:%S")
Hendry answered 17/7, 2018 at 13:25 Comment(0)
M
3

This should be a very common problem, hence contributing with a reproducible answer using dplyr:

## reproducible example
library(dplyr)
library(magrittr)
DF <- data.frame(Date = c("10/03/2014", "11/03/2014", "12/03/2014"),
                 Time = c("12.00.00", "13.00.00", "14.00.00"))

DF_DT <- DF %>% 
  mutate(DateTime = paste(Date, Time)) %>% 
  mutate(across('DateTime', ~ as.POSIXct(.x, format = "%d/%m/%Y %H.%M.%S")))
Mcnamee answered 6/1, 2021 at 22:12 Comment(0)
G
2

Use the package lubridate:

data$DT <- with(data, ymd(Date) + hms(Time))

If you want the column to be a POSIXct, do the following after that:

data$DT <- as.POSIXct(data$DT)
Giagiacamo answered 10/7, 2019 at 1:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.