1

In my dataframe I have two columns with times in format "HH:MM:SS" but in string, and I need to create a new column on this dataframe that stores the time difference in minutes of these two columns.

I've tried to use timediff() function but it wont work cause is not a date type, other methods that I saw only convert to "Month:day:year" etc... format, so...

Dataframe example:

       Id        time_1            time_2     
        1       "10:02:34"      "10:22:00"        
        2       "00:20:07"      "20:40:30"       
        3       "12:00:01"      "10:15:30"

I want something like:

   Id        time_1            time_2     difference    
    1       "10:02:34"      "10:22:00"       .... 
    2       "00:20:07"      "20:40:30"       ....
    3       "12:00:01"      "10:15:30"       ....
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
JediJesus
  • 329
  • 1
  • 9

1 Answers1

1

We can take the difference after converting to ITime

library(dplyr)
library(data.table)
df2 <- df1 %>%
     mutate(difference = as.ITime(time_2) - as.ITime(time_1))

or to get the difference in minutes

df1 %>% 
    mutate(difference = difftime(as.ITime(time_1),
      as.ITime(time_2), units = 'min'))
akrun
  • 874,273
  • 37
  • 540
  • 662