In R, Use Lubridate to Convert Hms Objects into Seconds

In R, use lubridate to convert hms objects into seconds

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>

How can we add time durations HMS formats in lubridate

a <- c("38:03:24", "6:50:58", "0:31:54", "8:13:51")

td <- as.period(seconds(sum(as.numeric(hms(a)))), unit = "hour")
# [1] "53H 40M 7S"
sprintf('%02d:%02d:%02d', td$hour, td$minute, td$second)
# [1] "53:40:07"

Retrieve time format to convert to seconds in R

Assuming that the input vector have only a single format, create a condition to check if the number of characters are '5', then paste '00:' at the beginnng and then apply only hms to convert to time format

f1 <- function(vec) {
if(all(nchar(vec)==5)) {
vec <- paste0("00:", vec)
}
vec %>%
hms() %>%
period_to_seconds()

}

f1(a)
#[1] 1 3 5
f1(b)
#[1] 1 3 5

lubridate fails when column contains both hms and ms

Or shorter with just base R:

a <- c("36:10", "1:06:32", NA)

a2 <- ifelse(nchar(a) < 6, paste0("00:", a), a)

hms(a2)

> hms(a2)
[1] "36M 10S" "1H 6M 32S" NA

Convert a duration %H:%M:%S to seconds

After we convert it to POSIXlt, extract the hour, min and sec and do the arithmetic

v1 <- strptime(durations, format='%H:%M:%S')
v1$hour * 3600 + v1$min * 60 + v1$sec
#[1] 3661

Or

c(unlist(unclass(v1)[c("hour", "min", "sec")]) %*% c(3600, 60, 1))

How to convert difftime to string X hours Y minutes Z seconds

It may be easier to convert to period if the units is seconds

library(lubridate)
seconds_to_period(difftime(hms::hms(11, 02, 03),
hms::hms(10, 00, 00), units = 'sec'))


Related Topics



Leave a reply



Submit