Lubridate can't round a Period object

1.1k views Asked by At

I'm trying to round a lubridate Period object to the nearest minute.

library(lubridate)
round_date(as.period("2d 20H 22M 9.57S"))

Gives

Error in as.POSIXct.numeric(x) : 'origin' must be supplied

So round_date is converting my period to a POSIXct, but why? Is it possible to round periods in lubridate without converting them to another format? Seems like I'm missing something simple.

Thanks!

3

There are 3 answers

0
Quentin On BEST ANSWER

Since this issue was opened, it is now possible to round a lubridate Period as shown in this thread. Here is the example in your case :

library("lubridate")  
round(as.period("2d 20H 22M 9.57S"))  
[1] "2d 20H 22M 10S"
1
Uwe On

According to ?round_date, the function expects as first argument a vector of date-time objects. Therefore, it isn't meant to be used on a period object.

An explanation why it isn't possible to round a period object in general can be found in ?as.period: The exact length of each time unit in a period will depend on when it occurs. [...] For example, when a leap second occurs one minute is longer than 60 seconds.

lubridate very carefully distinguishes between Duration, Interval, and Period classes.

0
Rafael Díaz On

I definitely think that the best option is to convert it to numeric, that is to say, in seconds, divide it by 60 to make it minutes, then multiply by 60 to make it seconds, round it up and then period. And then you will get the nearest minute.

seconds_to_period(round(as.numeric(as.period("2d 20H 22M 9.57S"))/60)*60)
[1] "2d 20H 22M 0S"

If you want to approximate the seconds you can do the following

seconds_to_period(round(as.numeric(as.period("2d 20H 22M 9.57S"))))
[1] "2d 20H 22M 10S"