How to make difftime work with times like 00:00 (tt:mm)

40 Views Asked by At

I have been using difftime to change the time points in my data from POSIXct format (%Y-%m-%d %H:%M:%S) to relative time in hours(starting at 0). This works fine, except I have some very few time points that are registered at exactly midnight (00:00:00). Then difftime computes the difference to the next time point as 24 hours. Is there a way around this?

In the context of my data, I could simply change those time point to 00:01:00 and it would be okay since I am working on the hour time-scale, but I would first try to find a solution.

1

There are 1 best solutions below

0
margusl On

From the description, it sounds like hms might be useful here:

library(dplyr, warn.conflicts = FALSE)

tibble(t = c("01:00:02", "00:00:01", "00:00:00")) |>
  mutate(t_hms = hms::parse_hms(t),
         tdiff = t_hms - hms::as_hms("00:00:00")
         )
#> # A tibble: 3 × 3
#>   t        t_hms    tdiff    
#>   <chr>    <time>   <drtn>   
#> 1 01:00:02 01:00:02 3602 secs
#> 2 00:00:01 00:00:01    1 secs
#> 3 00:00:00 00:00:00    0 secs

Created on 2024-02-06 with reprex v2.0.2