Search code examples
rdatetimeunix-timestamplubridate

How to use R to convert column of ISO Timestamp data into POSIXt?


I have a data frame that looks something like this:

tbl <- data.frame(ISO_Timestamp = c(1612972204, 1612972214, 1612972224, 1612972234), S1 = c(7056, 7101.1, 5145, 2198))

I want to convert the ISO_timestamp column into a date-time POSIXt format. I am able to convert single ISO_Timestamp timestamp objects like this:

lubridate::as_datetime(1612988995)
[1] "2021-02-10 20:29:55 UTC"

I tried this to convert the entire column but it is not working.

data_1 <- tbl %>% 
mutate(date_time = as_datetime(`ISO_Timestamp`))

I am getting the following error:

 Warning messages:
1: Problem with `mutate()` input `date_time`.
x All formats failed to parse. No formats found.
ℹ Input `date_time` is `as_datetime(`ISO_Timestamp`)`. 
2: All formats failed to parse. No formats found. 

What am I doing wrong?


Solution

  • The column name didn't had any spaces

    library(lubridate)
    library(dplyr)
    tbl %>% 
      mutate(date_time = as_datetime(ISO_Timestamp))
    

    -output

    # ISO_Timestamp     S1           date_time
    #1    1612972204 7056.0 2021-02-10 15:50:04
    #2    1612972214 7101.1 2021-02-10 15:50:14
    #3    1612972224 5145.0 2021-02-10 15:50:24
    #4    1612972234 2198.0 2021-02-10 15:50:34