Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Length of lubridate interval

Tags:

r

lubridate

What's the best way to get the length of time represented by an interval in lubridate, in specified units? All I can figure out is something like the following messy thing:

> ival
[1] 2011-01-01 03:00:46 -- 2011-10-21 18:33:44

> difftime(attr(ival, "start") + as.numeric(ival), attr(ival, "start"), 'days')
Time difference of 293.6479 days

(I also added this as a feature request at https://github.com/hadley/lubridate/issues/105, under the assumption that there's no better way available - but maybe someone here knows of one.)

Update - apparently the difftime function doesn't handle this either. Here's an example.

> (d1 <- as.POSIXct("2011-03-12 12:00:00", 'America/Chicago'))
[1] "2011-03-12 12:00:00 CST"
> (d2 <- d1 + days(1))  # Gives desired result
[1] "2011-03-13 12:00:00 CDT"
> (i2 <- d2 - d1)
[1] 2011-03-12 12:00:00 -- 2011-03-13 12:00:00 
> difftime(attr(i2, "start") + as.numeric(i2), attr(i2, "start"), 'days')
Time difference of 23 hours

As I mention below, I think one nice way to handle this would be to implement a /.interval function that doesn't first cast its input to a period.

like image 929
Ken Williams Avatar asked Jan 06 '12 23:01

Ken Williams


1 Answers

This question is really old, but I'm adding an update because this question has been viewed many times and when I needed to do something like this today, I found this page. In lubridate you can now do the following:

d1 <- ymd_hms("2011-03-12 12:00:00", tz = 'America/Chicago')
d2 <- ymd_hms("2011-03-13 12:00:00", tz = 'America/Chicago')

(d1 %--% d2)/dminutes(1)
(d1 %--% d2)/dhours(1)
(d1 %--% d2)/ddays(1)
(d1 %--% d2)/dweeks(1)
like image 55
Michael Dewar Avatar answered Nov 16 '22 04:11

Michael Dewar