NBK
NBK

Reputation: 905

r - Average timestamps excluding the day

I want to average two timestamps, but excluding the day. For example, I need the average of 9:00 AM of Monday and 10:00 AM of Tuesday to be just 9:30 AM.

Take the following code as example:

x$Hora.inicio[1]
[1] "2019-11-15 23:06:00 UTC"

class(x$Hora.inicio[1])
[1] "POSIXct" "POSIXt" 

mean(c(x$Hora.inicio[1], x$Hora.inicio[2]))
[1] "2019-11-16 10:16:00 UTC"

This outcome is not satisfactory. How do I average timestamps so that the result accounts only for the time but not the day?

PS: This, this and this question are similar to mine but don't address my specific question.

Upvotes: 0

Views: 57

Answers (2)

Patrick Roocks
Patrick Roocks

Reputation: 3259

I would first remove the "floored date" (0:00 on the same day), and then use the time difference of the dates. Works also if the original dates are in another time zone than UTC:

# input
d1 <- as.POSIXct("2019-11-15 23:06:00", tz = "UTC")
d2 <- as.POSIXct("2019-11-14 03:01:00", tz = "UTC")

# remove 0:00 of the same day (but keep time zone!)
remove_day <- function(d) {
  d - as.POSIXct(format(d, "%Y-%m-%d %Z"), tz = format(d1, "%Z"))
}
t1 <- remove_day(d1)
t2 <- remove_day(d2)

# average
mean_time <- mean(c(t1, t2))
# mean_time is now: "Time difference of 13.05833 hours"

# nicely formatted (date is arbitrary, won't be printed):
format(as.POSIXct("2010-01-01", tz = "UTC") + mean_time, "%H:%M:%S")  
# output: [1] "13:03:30"

Upvotes: 1

markhogue
markhogue

Reputation: 1179

The lubridate package can help. There's probably a function in the package that already does this, but I couldn't find it quickly. Here's a function you can use if you want the difference in seconds between two times, regardless of the date:

library(lubridate)

time_date2 <- now()
time_date1 <- time_date2 - 3600 * 20 #20 hours ago
time_length(time_date2 - time_date1)

time_sub_sec <- function(t1, t2) {
  (hour(time_date1) - hour(time_date2)) * 3600 + 
    (minute(time_date1) - minute(time_date2)) * 60 +
    second(time_date1) - second(time_date2)
}

time_sub_sec(time_date2, time_date1) # four hour time difference = 14400 seconds
#14400

Upvotes: 2

Related Questions