[英]Find mid time between two times in R, sometimes overnight
I would like to find the mid time between time 1 and time 2 in R.我想在 R 中找到时间 1 和时间 2 之间的中间时间。 I already have the duration in hours.
我已经有了以小时为单位的持续时间。 Sometimes it's overnight (row 1) and sometimes not (row 2).
有时是一夜之间(第 1 行),有时不是(第 2 行)。
Here are the first two rows in the data frame这是数据框中的前两行
dat <- data.frame(id=1:2, tm1=c("23:00","01:00"), tm2=c("07:00","06:00"), dur=c("8.0","5.0"))
So in row 1 the mid time should be 3:00 and in row 2 it should be 03:30.所以在第 1 行,中间时间应该是 3:00,在第 2 行应该是 03:30。
you can just add half of the duration你可以只添加一半的持续时间
format(strptime(dat$tm1,format = '%H:%M') + dat$dur*3600/2, format = '%H:%M')
Here is one way -这是一种方法 -
library(dplyr)
dat %>%
mutate(across(starts_with('tm'), as.POSIXct, tz = 'UTC', format = '%H:%M'),
tm2 = if_else(tm1 > tm2, tm2 + 86400, tm2),
midtime = tm1 + difftime(tm2, tm1, units = 'secs')/2,
across(c(starts_with('tm'), midtime), format, '%H:%M'))
# id tm1 tm2 dur midtime
#1 1 23:00 07:00 8.0 03:00
#2 2 01:00 06:00 5.0 03:30
The logic is -逻辑是——
tm1
and tm2
to POSIXct
class.tm1
和tm2
转换为POSIXct
class。 This will add today's date in both the columns.tm1 > tm2
(like in row 1) add 1 day to tm2
.tm1 > tm2
(如在第 1 行中)将 1 天添加到tm2
。tm1
to get midtime
.tm1
以获得midtime
。'%H:%M'
format in all columns.'%H:%M'
格式更改时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.