首页 > 解决方案 > 可以检查时间(无日期)是否在特定的日期时间间隔内?

问题描述

示例:我想检查 03:00 是否在 2015-01-05 00:52 和 2015-01-05 05:52 的区间内,对于这种情况,我想要的结果是 TRUE。

提前致谢

标签: rdatetime

解决方案


我为具有多个最大和最小日期时间的数据框提出了此解决方案(解决方案比创建可重现示例的行数短):

# Reproducible example
set.seed(666)
timeLimits <- seq(from = (as.POSIXct("1996-6-6 06:06:06")),
                  to = (as.POSIXct("1997-6-6 06:06:06")),
                  by = "hour")
timeLimits <- matrix(data = sort(sample(x = timeLimits, size = 66)), 
                     ncol = 2, byrow = TRUE)
timeLimits <- data.frame(min = as.POSIXct(x = timeLimits[,1], origin = "1970-1-1 00:00:00"),
                         max = as.POSIXct(x = timeLimits[,2], origin = "1970-1-1 00:00:00"))


# The solution
require(lubridate)

answer <- apply(timeLimits, 2, as.character)
answer <- apply(timeLimits, 1, function(x) is.element(3, hour(seq(as.POSIXct(x[1]), as.POSIXct(x[2]), "hour"))))

推荐阅读