r - 为交易时间生成时间序列
问题描述
我想创建一个序列,从 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
解决方案
我们可以使用创建一个函数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"
推荐阅读
- angular - 尝试使用 attach 方法在 VSCode 中调试 Angular 时我做错了什么?
- python - 无法使用 pipenv 安装 PyPi 库
- linux - 同一网络中的 Docker 容器无法相互通信
- python - 迭代使用 groupby 应用函数
- r - 使用 tidyverse 对分组数据执行除法运算
- database-normalization - 具有主键和唯一属性的功能依赖性
- pandas - 多个数据帧的内连接
- python - 随机数列表生成器未按预期工作(Python)
- c++ - 同一线程上的两个连续 memory_order_release 存储可以相互重新排序吗?
- python - 如何从 QLineEdit() 获取 int?