0

I have a df that contains two column with dates and time and i want to convert them from characters to date and time format. Could anyone help? Thank you

dput(df)
structure(list(start_date = c("2021-03-01 00:00:03", "2021-03-01 00:02:04", 
"2021-03-01 00:02:29"), finish_date = c("2021-03-01 00:16:29", 
"2021-03-01 00:35:40", "2021-03-01 00:33:14")), row.names = c(NA, 
3L), class = "data.frame")

i have tried this but didnt work

 as.Date.POSIXct(df$start_date, format="%Y/%m/%dT%H:%M:%S"

 as.Date.POSIXct(df$finish_date, format="%Y/%m/%dT%H:%M:%S"
Phil
  • 7,287
  • 3
  • 36
  • 66
pipts
  • 87
  • 7

1 Answers1

0
as.POSIXct('2021-03-01 00:03:04')

see: past question

Sweepy Dodo
  • 1,761
  • 9
  • 15
  • could you use `dput(df)` and paste R's output into your question? This is to make a re-producible dataset – Sweepy Dodo Feb 21 '22 at 19:36
  • i used the dput(df) to make the things easier. Could you help with the exact code I need to use in this dataframe to get the desired result? thank you – pipts Feb 21 '22 at 20:15
  • `df <- lapply(df, \(i) as.POSIXct(i))` works with the data you provided I ran `lapply(df, class)` to check all columns' class which returned `"POSIXct" "POSIXt"` – Sweepy Dodo Feb 21 '22 at 20:35
  • Use the below to apply to specific columns: `x <- c('start_date', 'finish_date'); df[x] <- lapply(df[x], \(i) as.POSIXct(i))` – Sweepy Dodo Feb 21 '22 at 20:41