Alessandro Jacopson
Alessandro Jacopson

Reputation: 18705

Is it possible to print a duration with HH:MM:SS format?

t1<-as.POSIXct("2017-03-02 11:58:20")
t2<-as.POSIXct("2017-03-02 12:00:05")
print(lubridate::as.duration(lubridate::interval(t1,t2)))

[1] "105s (~1.75 minutes)"

Is it possible to have the duration expressed in HH:MM:SS? So in this case it would be:

00:01:45

Upvotes: 4

Views: 3262

Answers (3)

jay.sf
jay.sf

Reputation: 73802

In base R we can do

> strftime(diff(sapply(list(t1, t2), as.numeric)), '%H:%M:%S', tz='UTC')
[1] "00:01:45"

Data:

> dput(t1)
structure(1488452300, class = c("POSIXct", "POSIXt"), tzone = "")
> dput(t2)
structure(1488452405, class = c("POSIXct", "POSIXt"), tzone = "")

Upvotes: 1

takje
takje

Reputation: 2800

To stay in the lubridate mindset:

t1<-as.POSIXct("2017-03-02 11:58:20")
t2<-as.POSIXct("2017-03-02 12:00:05")
dur <- lubridate::as.period(lubridate::as.duration(lubridate::interval(t1,t2)))
sprintf('%02d %02d:%02d:%02d', day(dur), hour(dur), minute(dur), second(dur))

Normally, the period class might be inaccurate (leap days etc) but since it was first passed through duration, it should be right.

Upvotes: 3

Karthik Arumugham
Karthik Arumugham

Reputation: 1360

You can use seconds_to_period from lubridate with sprintf

library(lubridate)
td <- seconds_to_period(difftime(t2, t1, units = "secs"))
sprintf('%02d:%02d:%02d', td@hour, minute(td), second(td))
#[1] "00:01:45"

This is based on an earlier discussion - Converting seconds to days: hours:minutes:seconds in r?

Upvotes: 5

Related Questions