How to process only part of a string into a date in R

Viewed 53

I have some data from an api that gives timestamps in an unusual format that includes day of the week and day of the year at the end. For example [2021, 8, 22, 22, 0, 20, 6, 234] is 2021/08/22 22:00:20 on the 6th day of the week, 234th day of the year. I want to convert this into a lubridate date-time object but don't know how to strip out the last two values.

For example I'd like to take this data

example <- tibble(timestamp = c("[2021, 8, 22, 22, 0, 20, 6, 234]", "[2021, 8, 22, 22, 0, 30, 6, 234]", "[2021, 8, 22, 22, 0, 41, 6, 234]"), temperature = c(28,29,30)) and turn the timestamp column into a lubridate date-time type. Any ideas?

2 Answers

You can use strptime and then supply a proper format string

example %>% dplyr::mutate(
  datetime = strptime(timestamp, format = "[%Y, %m, %d, %H, %M, %S"))

# A tibble: 3 x 3
  timestamp                        temperature datetime           
  <chr>                                  <dbl> <dttm>             
1 [2021, 8, 22, 22, 0, 20, 6, 234]          28 2021-08-22 22:00:20
2 [2021, 8, 22, 22, 0, 30, 6, 234]          29 2021-08-22 22:00:30
3 [2021, 8, 22, 22, 0, 41, 6, 234]          30 2021-08-22 22:00:41

How about this.

library(tidyverse)

example <- tibble(timestamp = c("[2021, 8, 22, 22, 0, 20, 6, 234]", "[2021, 8, 22, 22, 0, 30, 6, 234]", "[2021, 8, 22, 22, 0, 41, 6, 234]"), temperature = c(28,29,30))

example %>%
  mutate(timestamp = str_split(timestamp, ","),
         timestamp = map_chr(timestamp, ~paste(parse_number(.x[1:6]), collapse = ".")),
         timestamp = lubridate::ymd_hms(timestamp))
#> # A tibble: 3 x 2
#>   timestamp           temperature
#>   <dttm>                    <dbl>
#> 1 2021-08-22 22:00:20          28
#> 2 2021-08-22 22:00:30          29
#> 3 2021-08-22 22:00:41          30

I just split the list, parse the numbers to remove the brackets, then collapse the list omitting the last two elements, and lastly parse the date time.

Related