In R, use lubridate to convert hms to seconds

simple question in lubridate - I want to convert an hms object to the appropriate number of seconds from the beginning of the day.

for instance

library(lubridate) hms("12:34:45") 

then I want to know exactly how long 12 hours, 34 minutes and 45 seconds, in seconds

something obvious like

 seconds(hms("12:34:45")) 

just returns

 45s 

what I do not want. How to convert these hms values ​​to seconds? I would like to use lubridate

+4
source share
2 answers

It does not matter which package you use - it converts the date / datetime object to a POSIXct representation of seconds from the era. So you can also do this in the R database - 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 need 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 use for 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 returning to lubridate, this is possibly a mistake:

 > 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> 
+8
source
 R>lubridate::period_to_seconds(hms("01:00:00")) 

gives the expected 3600 seconds as a numerical count from 00:00:00 or in the above case:

 R>period_to_seconds(hms("12:34:45")) 
+18
source

All Articles