Get time from xts index

r xts
E.D. picture E.D. · Oct 13, 2011 · Viewed 11k times · Source

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?

Answer

Roman Luštrik picture Roman Luštrik · Oct 13, 2011

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"