sbha
sbha

Reputation: 10422

R Calculating overnight time difference (when start time is PM and end time is AM of the next day)

I need the difference in hours between a shift start and end time. The start and end times are character strings in a 12 hour am/pm format. We can assume the start times are all on the same calandar day, but end times can go to the following day (overnight shifts). difftime treats them as on the same date, resulting in differences that calculate in the wrong direction: if start time is 7:00 PM and end time is 4:00 AM, a 9 hour shift is calculated as 15 hours. Is it possible to calculate these time differences without creating a more complicated function?

df= structure(c("7:00 AM", "7:00 PM", "8:00 AM", "10:00 PM", 
            "4:00 PM", "4:00 AM", "5:00 PM", "6:00 AM"), .Dim = c(4L, 2L))

as.numeric(difftime(
   strptime(df[,2], "%I:%M %p" ),
   strptime(df[,1], "%I:%M %p" ),
   units='hours'))
[1]   9 -15   9 -16

The results I'm looking for should be:

[1] 9 9 9 8 

Upvotes: 3

Views: 1231

Answers (1)

vpipkt
vpipkt

Reputation: 1707

This should do it.

shift.dur <- function(m){
    hours<- as.numeric(difftime(
        strptime(df[,2], "%I:%M %p" ),
        strptime(df[,1], "%I:%M %p" ),
        units='hours'))
    hours[hours<0] <- 24+hours[hours<0] 
    hours
}

Upvotes: 4

Related Questions