如果您想处理时间和日期,POSIXlt 类很有帮助。如果您的时间戳是
存储为字符串,第一步是将它们转换为 POSIXlt。您可以为此使用“strptime”,例如
> t <- strptime("2015-01-01 12:18",format="%Y-%m-%d %H:%M")
> t
[1] "2015-01-01 12:18:00 CET"
> class(t)
[1] "POSIXlt" "POSIXt"
>
下面的函数“timerange”为这样一个POSIXlt对象分配一个时间范围号:
R <- list( Sun = list(),
Mon = list( c("10:00","10:30"), c("12:15","12:40"), c("13:15","13:40") ),
Tue = list( c( "9:10", "9:40"), c("11:00","11:30"), c("13:15","13:40") ),
Wed = list( c("10:00","10:30"), c("12:15","12:40"), c("13:15","13:40") ),
Thu = list( c("10:00","10:30"), c("12:15","12:40"), c("13:15","13:40") ),
Fri = list( c("10:00","10:30"), c("12:15","12:40"), c("13:15","13:40") ),
Sat = list( c("10:00","10:30"), c("12:15","12:40"), c("13:15","13:40") ) )
timerange <- function(t)
{
s <- unlist(strsplit(strftime(t,format="%Y-%m-%d %H:%M:%S %w")," "))
w <- as.numeric(s[3]) + 1
n <- sapply(R[[w]], function(x){ strptime(paste(s[1]," ",x,":00",sep=""),
format="%Y-%m-%d %H:%M:%S")})
return( which(sapply(n,function(x){ t-x[1]>=0 & t-x[2]<=0})) )
}
“R”是所有时间范围的列表。你可以随意改变它。
"strftime" 是 "strptime" 的对应物,即将 POSIXlt 对象 "t" 转换为
所需格式的字符串。然后将这个字符串吐到日期部分,时间部分,
和星期几。后者用于在“R”中选择适当的子列表。
然后“strptime”用于创建成对的 POSIXlt 对象列表。时间部分来自
“R”的适当子列表,日期部分来自“t”。每个这样的对代表一个时间间隔。
那么时间范围号就是包含“t”的时间区间的索引。
一些例子:
> t <- strptime("2015-01-01 12:18",format="%Y-%m-%d %H:%M")
> timerange(t)
[1] 2
> t <- strptime("2015-01-05 10:01",format="%Y-%m-%d %H:%M")
> timerange(t)
[1] 1
> t <- strptime("05.01.2015 13:25",format="%d.%m.%Y %H:%M")
> timerange(t)
[1] 3