Extracting time from POSIXct

You can use strftime to convert datetimes to any character format:

> t <- strftime(times, format="%H:%M:%S")
> t
 [1] "02:06:49" "03:37:07" "00:22:45" "00:24:35" "03:09:57" "03:10:41"
 [7] "05:05:57" "07:39:39" "06:47:56" "07:56:36"

But that doesn’t help very much, since you want to plot your data. One workaround is to strip the date element from your times, and then to add an identical date to all of your times:

> xx <- as.POSIXct(t, format="%H:%M:%S")
> xx
 [1] "2012-03-23 02:06:49 GMT" "2012-03-23 03:37:07 GMT"
 [3] "2012-03-23 00:22:45 GMT" "2012-03-23 00:24:35 GMT"
 [5] "2012-03-23 03:09:57 GMT" "2012-03-23 03:10:41 GMT"
 [7] "2012-03-23 05:05:57 GMT" "2012-03-23 07:39:39 GMT"
 [9] "2012-03-23 06:47:56 GMT" "2012-03-23 07:56:36 GMT"

Now you can use these datetime objects in your plot:

plot(xx, rnorm(length(xx)), xlab="Time", ylab="Random value")

enter image description here


For more help, see ?DateTimeClasses

Leave a Comment