In R, use lubridate to convert hms objects into seconds

后端 未结 2 819
刺人心
刺人心 2021-02-15 03:12

simple question in lubridate--I want to convert an hms object into its appropriate number of seconds since the start of the day.

For instance

library(lub         


        
2条回答
  •  暖寄归人
    2021-02-15 04:06

    It doesn't matter which package you use -- it will have convert a date / datetime object into a POSIXct representation of seconds since the epoch. So you may as well do it in base R -- so here deploy ISOdatetime() with an arbitrary day, using today:

    R> difftime(ISOdatetime(2012,7,2,12,34,45), ISOdatetime(2012,7,2,0,0,0))
    Time difference of 12.5792 hours
    

    So we want seconds:

    R> difftime(ISOdatetime(2012,7,2,12,34,45), ISOdatetime(2012,7,2,0,0,0), 
    +          unit="secs")
    Time difference of 45285 secs
    

    And we can cast to numbers:

    R> as.numeric(difftime(ISOdatetime(2012,7,2,12,34,45), +
                           ISOdatetime(2012,7,2,0,0,0), unit="secs"))
    [1] 45285
    

    Edit: And getting back to lubridate, this is arguably a bug:

    > hms("12:34:45") - hms("00:00:00")
    [1] 12 hours, 34 minutes and 45 seconds
    R> as.numeric(hms("12:34:45") - hms("00:00:00"))
    [1] 45
    R>
    

提交回复
热议问题