'How to extract number of days from seconds_to_period function in R

I put number of second into seconds_to_period() function and here is my code:

my_time_sum <- seconds_to_period(my_time_seconds_sum)  # Convert seconds to Period
my_time_sum

Output:

[1] "144d 12H 53M 19S"

I was just curious how can I extract '144' out of this string? Also, are there any ways to convert this duration to number of years?



Solution 1:[1]

The day() function (and related lubridate unit functions year() etc.) have methods for Period class so you can use:

library(lubridate)

day(my_time_sum)
[1] 144
 

Solution 2:[2]

Just carry out an integer division. ie:

my_time_sum <- seconds_to_period(10000000)
my_time_sum %/% days(1)
[1] 115

If you want to convert to number of years, divide by years: ie

my_time_sum /years(1)
[1] 0.3168809

Solution 3:[3]

You can extract individual components using $ like this:

my_time_sum$day

You can extract $year, $month, $day, $hour, $minute, and the confusingly-named $.Data for seconds.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ritchie Sacramento
Solution 2 onyambu
Solution 3 Michael Dewar