【发布时间】:2011-10-13 15:58:40
【问题描述】:
我有一个 xts 对象,x。我想根据索引中的时间戳运行一个 for 循环直到某个时间。
> index(x)
[1] "2011-10-12 16:44:00 SAST"
假设我想运行我的循环,只要索引中的时间小于 16:40:00。给定上述索引的格式,如何去除时间分量?
【问题讨论】:
我有一个 xts 对象,x。我想根据索引中的时间戳运行一个 for 循环直到某个时间。
> index(x)
[1] "2011-10-12 16:44:00 SAST"
假设我想运行我的循环,只要索引中的时间小于 16:40:00。给定上述索引的格式,如何去除时间分量?
【问题讨论】:
这应该会让你进入你想去的地方。使用format,您只提取小时、分钟和秒部分。 ?strptime 的帮助页面提供了有关用于提取信息的符号的更多详细信息。
#if you don't have your string in an appropriate format yet
(x <- strptime("2011-10-12 16:44:00 SAST", format = "%Y-%m-%d %H:%M:%S"))
[1] "2011-10-12 16:44:00"
class(x)
[1] "POSIXlt" "POSIXt"
(new.x <- format(x, format = "%H:%M:%S"))
[1] "16:44:00"
【讨论】:
问题在于正确设置时区。在我的系统上,“SAST”的 tz 规范无效,但在你的系统上它可能是:
x[ index(x) < as.POSIXct( "2011-10-12 16:44:00", tz= SAST") ]
(似乎是 UTC +2。)我收回我所说的关于我的系统无法识别它的内容。
as.POSIXct( "2011-10-12 16:44:00", tz= "Africa/Johannesburg")
# [1] "2011-10-12 16:44:00 SAST"
所以使用:
x[ index(x) <= as.POSIXct( "2011-10-12 16:44:00", tz= "Africa/Johannesburg")]
【讨论】: