首页 > 解决方案 > 为交易时间生成时间序列

问题描述

我想创建一个序列,从 Sys.time() 到指定的结束日期,我在上午 9:30 和下午 4:00 生成点。

#So for example if:
end.date = 2019-04-12 
Sys.time() = 2019-04-10 12:00 #the sequence should look like this.

2019-04-10 12:00
2019-04-10 16:00
2019-04-11 09:30
2019-04-11 16:00
2019-04-12 09:30
2019-04-12 16:00

#The goal is to put it into a function where the output would be :

x = function(Sys.time(), end.date)
print(x)
 2019-04-10 12:00
 2019-04-10 16:00
 2019-04-11 09:30
 2019-04-11 16:00
 2019-04-12 09:30
 2019-04-12 16:00

标签: rtime-series

解决方案


我们可以使用创建一个函数outer

get_date_time <- function(start.date, end.date, times) {
  c(outer(seq(as.Date(start.date), as.Date(end.date), by = "1 day"), 
  times, paste, sep = " "))
}

get_date_time("2019-04-10","2019-04-12",c("09:30:00", "16:30:00"))

#[1] "2019-04-10 09:30:00" "2019-04-11 09:30:00" "2019-04-12 09:30:00" 
#[4] "2019-04-10 16:30:00" "2019-04-11 16:30:00" "2019-04-12 16:30:00"

以上以字符格式返回输出。如果您需要一个日期时间对象,并且值的顺序也很重要,我们可以使用as.POSIXct它们sort

get_date_time <- function(start.date, end.date, times) {
   sort(as.POSIXct(outer(seq(as.Date(start.date), as.Date(end.date), by = "1 day"), 
   times, paste, sep = " ")))
}

#[1] "2019-04-10 09:30:00 +08" "2019-04-10 16:30:00 +08" "2019-04-11 09:30:00 +08" 
#[4] "2019-04-11 16:30:00 +08" "2019-04-12 09:30:00 +08" "2019-04-12 16:30:00 +08"

推荐阅读