Saving and readings lubridate intervals to/from disk

76 views Asked by At

I am having problems recovering lubridate::intervals when reading back from csv, and fst formats.

Does anyone have a suggestion for how to do this?

library(tidyverse)
library(fst)
library(lubridate)

test <- tibble(
  start = ymd_hms("2020-01-01 12:13:14", tz="UTC"),
  end   = ymd_hms("2021-01-01 12:13:14", tz="UTC"),
  interval = lubridate::interval(start, end)
) %>% 
  write_csv("test1.csv")
test %>% fst::write_fst("test1.fst")

str(test)

test_read_back_csv <- read_csv("test1.csv")
str(test_read_back_csv)

test_read_back_fst <- read_fst("test1.fst")
str(test_read_back_fst)

You will see that the structure of the returned object test_read_back_csv$interval or test_read_back_fst$interval is not a lubridate interval, and I both need to save this file, and read it back properly.

1

There are 1 answers

0
zephryl On

Save to a binary format such as .RDS:

str(test)

#> tibble [1 x 3] (S3: tbl_df/tbl/data.frame)
#>  $ start   : POSIXct[1:1], format: "2020-01-01 12:13:14"
#>  $ end     : POSIXct[1:1], format: "2021-01-01 12:13:14"
#>  $ interval:Formal class 'Interval' [package "lubridate"] with 3 slots
#>   .. ..@ .Data: num 31622400
#>   .. ..@ start: POSIXct[1:1], format: "2020-01-01 12:13:14"
#>   .. ..@ tzone: chr "UTC"

write_rds(test, "test1.rds")
test_read_back_rds <- read_rds("test1.rds")
str(test_read_back_rds)

#> tibble [1 x 3] (S3: tbl_df/tbl/data.frame)
#>  $ start   : POSIXct[1:1], format: "2020-01-01 12:13:14"
#>  $ end     : POSIXct[1:1], format: "2021-01-01 12:13:14"
#>  $ interval:Formal class 'Interval' [package "lubridate"] with 3 slots
#>   .. ..@ .Data: num 31622400
#>   .. ..@ start: POSIXct[1:1], format: "2020-01-01 12:13:14"
#>   .. ..@ tzone: chr "UTC"

Created on 2022-03-14 by the reprex package (v2.0.1)