Extracting time from POSIXct

后端 未结 6 721
梦如初夏
梦如初夏 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:09

    There have been previous answers that showed the trick. In essence:

    • you must retain POSIXct types to take advantage of all the existing plotting functions

    • if you want to 'overlay' several days worth on a single plot, highlighting the intra-daily variation, the best trick is too ...

    • impose the same day (and month and even year if need be, which is not the case here)

    which you can do by overriding the day-of-month and month components when in POSIXlt representation, or just by offsetting the 'delta' relative to 0:00:00 between the different days.

    So with times and val as helpfully provided by you:

    ## impose month and day based on first obs
    ntimes <- as.POSIXlt(times)    # convert to 'POSIX list type'
    ntimes$mday <- ntimes[1]$mday  # and $mon if it differs too
    ntimes <- as.POSIXct(ntimes)   # convert back
    
    par(mfrow=c(2,1))
    plot(times,val)   # old times
    plot(ntimes,val)  # new times
    

    yields this contrasting the original and modified time scales:

    enter image description here

提交回复
热议问题