Problem to calculated time duration (secs) without date given

Hi,
I bump into a problem where I need to compute the duration from session_start_text and session_end_text
However, the data does not give the date information, so when the session_end_text is 00:01:00, means the day after, which makes duration is negative

session        session_start_text session_end_text clickouts booking duration
  <chr>          <time>             <time>               <dbl>   <dbl>    <dbl>
1 20170503000001 06:11:53           06:15:11                 3       0      198
2 20170503000002 21:06:41           21:08:23                 3       0      102
3 20170503000003 12:03:01           12:06:02                 3       0      181
4 20170503000004 05:58:00           06:02:56                 0       0      296
5 20170503000005 09:13:43           09:17:01                 1       0      198
6 20170503000006 01:27:37           01:30:23                 4       0      166

Here is the code I run to find the duration

session_data$duration <- as.numeric(session_data$session_end_text-session_data$session_start_text,units="secs")

I tried to use If function to transformed it but did not work

session_data$session_end_text_transformed <- if(as.time(session_data$session_end_text<00:10:00)){
+ as.time(session_data$session_end_text_transformed + 24:00:00)
+ } else {as.time(session_data$session_end_text)}

Maybe the code I tried to transformed is wrong, if you can come up with easier way. Please let me know
TIA.

I would use logic like the following code where I add one day (86400s) if the End time is less than the start.

library(hms)
DF <- data.frame(Start=as_hms(c("08:03:32","21:13:45")),
                 End=as_hms(c("10:16:11","01:06:12")))
DF$duration <- DF$End - DF$Start + 86400 * (DF$End < DF$Start)
DF
#>      Start      End   duration
#> 1 08:03:32 10:16:11  7959 secs
#> 2 21:13:45 01:06:12 13947 secs

Created on 2022-01-22 by the reprex package (v2.0.1)

Hi FJCC

That works perfectly, thank you.
Maybe a stupid question, I assume that this part means IF * (DF$End < DF$Start) but why does it come with an asterisk (*) ?

@FJCC's answer is using an interesting bit of R strangeness! The asterisk means what it always means - multiplication. Look here for a generic example of what FJCC is doing (remember that DF$End < DF$Start evaluates to either TRUE or FALSE):

> TRUE == 1
[1] TRUE
> FALSE == 0
[1] TRUE
> 10 + 5 * TRUE
[1] 15
> 10 + 5 * FALSE
[1] 10
1 Like

Thank you so much!
That explains it :slight_smile:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.