Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R, use lubridate to convert hms objects into seconds

Tags:

r

lubridate

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(lubridate)
hms("12:34:45")

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

something obvious like

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

just returns

45s

which is not what I want. How do I convert these hms values into seconds? I'd like to use lubridate

like image 833
tomw Avatar asked Jul 02 '12 17:07

tomw


People also ask

How do I convert seconds to minutes in R?

First, you are converting the seconds into a Period (lubridate's object to represent time lapses) using seconds_to_period() function. The result of that looks like this "2H 23M 20S" Then, using hour() and minute() you can extract the units you need, in this case hours and minutes.

What is HMS time?

Converts a fractional part of a serial Julian date and time into hours, minutes and seconds.


2 Answers

R>lubridate::period_to_seconds(hms("01:00:00")) 

gives expected 3600 seconds as numeric counting from 00:00:00 or in the case above:

R>period_to_seconds(hms("12:34:45")) 
like image 83
Steven Varga Avatar answered Nov 10 '22 05:11

Steven Varga


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>
like image 32
Dirk Eddelbuettel Avatar answered Nov 10 '22 04:11

Dirk Eddelbuettel