6

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?

E.D.
  • 319
  • 1
  • 5
  • 15

2 Answers2

4

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"
Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
  • thanks, works a charm. one question though, in order to compare this time component to an arbitrary time, say 16:00:00, how would I go about it? I have tried: if(new.x > strptime("16:00:00", "%H:%M:%S"), but it does not seem to pick it up, as the new.x is an historic value and the new time has today's date – E.D. Oct 13 '11 at 10:39
  • @E.D. I guess could create a new variable with date attached, or have your current variable with date as well. – Roman Luštrik Oct 13 '11 at 11:49
2

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")]
IRTFM
  • 258,963
  • 21
  • 364
  • 487