Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the time difference with minutes and seconds?

Tags:

time

r

I have two columns of time information using minutes and seconds in a data.frame without additional date information, now I want to calculate the difference between these two columns and get a new column for diff_time (end_time-start_time) in either seconds (diff_time1) or in minutes and seconds as expressed in the original variables(diff_time2), how can I calculate this in R? For example:

      start_time  end_time  diff_time1  diff_time2
       12'10"     16'23"      4'13"      253
       1'05"      76'20"      75'15"     4515  
       96'10"     120'22"     24'12"     1452
like image 696
johnsonzhj Avatar asked Nov 03 '25 22:11

johnsonzhj


1 Answers

Assuming that your times are stored as strings, in which case the quote denoting seconds must be escaped:

times <- data.frame(start_time = c("12'10\"", "1'05\"", "96'10\""),
                    end_time   = c("16'23\"", "76'20\"", "120'22\"")
                   )

Then you can use lubridate::ms to convert to minutes + seconds and do the calculations. You'll need to do some additional text conversions if you want the results for diff_time1 as strings:

library(lubridate)
library(dplyr)

times %>% 
  mutate(diff_time1 = ms(end_time) - ms(start_time)) %>%
  mutate(diff_time2 = as.numeric(diff_time1)) %>%
  mutate(diff_time1 = gsub("M ", "'", diff_time1)) %>% 
  mutate(diff_time1 = gsub("S", "\"", diff_time1))

  start_time end_time diff_time1 diff_time2
1     12'10"   16'23"      4'13"        253
2      1'05"   76'20"     75'15"       4515
3     96'10"  120'22"     24'12"       1452
like image 125
neilfws Avatar answered Nov 07 '25 16:11

neilfws



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!