Search code examples
rdplyrdata-sciencetidyverse

How to calculate time diff and get the result in time format


I want diff time in time for the table below

A B
30/07/2021 23:58 30/07/2021 23:59
30/07/2021 23:58 30/07/2021 23:58
30/07/2021 23:58 30/07/2021 23:58
30/07/2021 23:58 30/07/2021 23:58
30/07/2021 23:58 30/07/2021 23:58
30/07/2021 23:57 30/07/2021 23:58
30/07/2021 23:57 30/07/2021 23:58
30/07/2021 23:57 30/07/2021 23:58

all the methods have tried keep giving results like 1sec, but I want the result in time format like 00:00:02

this is the method I've tried below processing_time =difftime(time1 = Date , time2 = `Updated Time`, units = "secs")


Solution

  • Let's assume you have this data in a data.frame but have not yet converted the date-time values to POSIXct class. The this might succeed:

    dat$processing_time <- with(dat, difftime( as.POSIXct(B, format="%d/%m/%Y %H:%M") , 
                                               as.POSIXct(A, format="%d/%m/%Y %H:%M")))
    
    > dat
                     A                B processing_time
    1 30/07/2021 23:58 30/07/2021 23:59         60 secs
    2 30/07/2021 23:58 30/07/2021 23:58          0 secs
    3 30/07/2021 23:58 30/07/2021 23:58          0 secs
    4 30/07/2021 23:58 30/07/2021 23:58          0 secs
    5 30/07/2021 23:58 30/07/2021 23:58          0 secs
    6 30/07/2021 23:57 30/07/2021 23:58         60 secs
    7 30/07/2021 23:57 30/07/2021 23:58         60 secs
    8 30/07/2021 23:57 30/07/2021 23:58         60 secs
    

    Then you need to get that data in a form that format.POSIXt will respect:

    Perhaps:

     format(as.POSIXct(Sys.Date())+dat$processing_time, "%H:%M:%S")
    

    You might need to add or subtract hours to get that to appear correct since you probably did as I did and didn't enter a timezone so GMT was assumed.