Extracting time from POSIXct

后端 未结 6 718
梦如初夏
梦如初夏 2020-11-28 23:02

How would I extract the time from a series of POSIXct objects discarding the date part?

For instance, I have:

times <- structure(c(1331086009.5009         


        
6条回答
  •  星月不相逢
    2020-11-28 23:18

    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

提交回复
热议问题