Home > OS >  Convert factor to datetime in R
Convert factor to datetime in R

Time:05-18

I have a colum that is of factor datatype, however the timestamp is in this format:

%Y-%m-%dT%H:%M:%S

 $ fg_stop_time      : Factor w/ 8 levels "2022-05-16T20:38:19",..: 4 8

I cant seem to get the as.character to work it keeps coming up as NA

df$new_time <-strptime(x = as.character(df1$fg_stop_time), format = "%Y-%m-%d %H:%M:%S")

I think it has to do with the fact that there is the T character in-between. How do I get it to recognize the 'T'?

CodePudding user response:

How about this with lubridate ?

x <- as.factor("2022-05-16T20:38:19")

library(lubridate)

y <- ymd_hms(x)

str(y)

POSIXct[1:1], format: "2022-05-16 20:38:19"

CodePudding user response:

Just add the T within the format in strptime or as.POSIXct (it may be better to use as.POSIXct as strptime returns a list with POSIXlt class

as.POSIXct("2022-05-16T20:38:19", format = "%FT%T")
  • Related