Creating a function to change a variable type to time

Viewed 16

I'm playing around with functions in R and want to create a function that takes a character variable and converts it to a POSIXct.

The time variable currently looks like this:

"2020-01-01T05:00:00.283236Z"

I've successfully converted the time variable in my janviews dataset with the following code:

janviews$time <- gsub('T',' ',janviews$time)
janviews$time <- as.POSIXct(janviews$time, format = "%Y-%m-%d %H:%M:%S", tz = Sys.timezone())

Since I have to perform this on multiple datasets, I want to create a function that will perform this. I created the following function but it doesn't seem to be working and I'm not sure why:

set.time <- function(dat, variable.name){
  dat$variable.name <- gsub('T', ' ', dat$variable.name)
  dat$variable.name <- as.POSIXct(dat$variable.name, format = "%Y-%m-%d %H:%M:%S", tz = Sys.timezone())
}

Here's the first four rows of the janviews dataset:

structure(list(customer_id = c("S4PpjV8AgTBx", "p5bpA9itlILN", 
"nujcp24ULuxD", "cFV46KwexXoE"), product_id = c("kq4dNGB9NzwbwmiE", 
"FQjLaJ4B76h0l1dM", "pCl1B4XF0iRBUuGt", "e5DN2VOdpiH1Cqg3"), 
    time = c("2020-01-01T05:00:00.283236Z", "2020-01-01T05:00:00.895876Z", 
    "2020-01-01T05:00:01.362329Z", "2020-01-01T05:00:01.873054Z"
    )), row.names = c(NA, -4L), class = c("data.table", "data.frame"
), .internal.selfref = <pointer: 0x1488180e0>)

Also, if there is a better way to convert my time variable, I am open to changing my method!

1 Answers

I would use the lubridate package and the as_datetime() function.

lubridate::as_datetime("2020-01-01T05:00:00.283236Z")

Returns "2020-01-01 05:00:00 UTC"

Lubridate Info

Related