thentangler
thentangler

Reputation: 1256

Convert factor to datetime in R

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'?

Upvotes: 1

Views: 72

Answers (2)

akrun
akrun

Reputation: 887251

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")

Upvotes: 2

TTS
TTS

Reputation: 1928

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"

Upvotes: 3

Related Questions