[英]It is possible to check if a time (no date) is in specific datetime interval?
示例:我想檢查 03:00 是否在 2015-01-05 00:52 和 2015-01-05 05:52 的區間內,對於這種情況,我想要的結果是 TRUE。
提前致謝
更新
library(data.table)
as.ITime("03:00") %in% as.ITime( seq( as.POSIXct("2015-01-04 22:52"),
as.POSIXct("2015-01-05 05:52"),
by = 1 ) )
#[1] TRUE
舊答案
as.ITime("03:00") %between% c(as.ITime("2015-01-05 00:52"),
as.ITime("2015-01-05 05:52"))
#[1] TRUE
您可以通過在string
s 上玩一些技巧來嘗試下面的代碼
> match(x, sort(c(x, gsub(".*\\s", "", c(start, end))))) == 2
[1] TRUE
在哪里
start <- "2015-01-05 00:52"
end <- "2015-01-05 05:52"
x <- "3:00"
我為具有多個最大和最小日期時間的數據框提出了此解決方案(解決方案比創建可重現示例的行數短):
# 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"))))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.