从xts索引获取时间

发布于 2024-12-09 08:06:56 字数 178 浏览 0 评论 0原文

我有一个 xts 对象 x。我想根据索引中的时间戳运行 for 循环直到某个时间。

> index(x)
[1] "2011-10-12 16:44:00 SAST"

假设只要索引中的时间小于 16:40:00,我就想运行循环。考虑到上面索引的格式,如何去掉时间部分?

I have an xts object, x. I want to run a for loop until a certain time, based on the time stamp in the index.

> index(x)
[1] "2011-10-12 16:44:00 SAST"

Lets say I want to run my loop as long as the time in the index is less than say 16:40:00. How do I strip out the time component, given the format of the index above?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

命硬 2024-12-16 08:06:56

这应该能让你到达你想去的地方。使用 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"

This should get you in the ball park of where you want to be. Using format, you extract just the hours, minutes and seconds part. Help page for ?strptime gives more details about the symbols used for extraction of information.

#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"
空袭的梦i 2024-12-16 08:06:56

问题是使时区正确。在我的系统上,“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")]

The problem is getting the timezone correct. On my system the tz spec of "SAST" is not valid but perhaps on yours it will be:

x[ index(x) < as.POSIXct( "2011-10-12 16:44:00", tz= SAST") ]

(Appears to be UTC +2. ) And I take back what I said about my system not recognizing it.

 as.POSIXct( "2011-10-12 16:44:00", tz= "Africa/Johannesburg")
# [1] "2011-10-12 16:44:00 SAST"

So use:

x[ index(x) <= as.POSIXct( "2011-10-12 16:44:00", tz= "Africa/Johannesburg")]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文