Convert hms Object into Seconds in R (Example)
In this article, I’ll show how to transform hours, minutes, and seconds into seconds only in R.
Table of contents:
Let’s get started!
Creation of Example Data
Consider the following example data:
my_hms <- c("00:10:25", # Create vector of hms strings "00:04:04", "00:01:20", "00:11:42") my_hms # Print vector of hms strings #  "00:10:25" "00:04:04" "00:01:20" "00:11:42"
As you can see based on the previous output of the RStudio console, our example data is a vector object containing four hours, minutes, and seconds (hms) elements.
Let’s check the class of our example data:
class(my_hms) # Check class of data object #  "character"
At this point, our data has the character class.
Example: Convert hms Object to Seconds Using period_to_seconds() Function of lubridate Package
To be able to use the functions of the lubridate package, we first need to install and load lubridate:
install.packages("lubridate") # Install lubridate package library("lubridate") # Load lubridate package
In the next step, we can apply the hms function of the lubridate package to convert our character string to Period object:
my_hms_lubri <- lubridate::hms(my_hms) # Convert character to Period my_hms_lubri # Print Period object #  "10M 25S" "4M 4S" "1M 20S" "11M 42S"
As you can see, our data already looks different (even though we are not quite there yet).
Let’s check the data type of our updated data:
class(my_hms_lubri) # Check class of data object #  "Period" # attr(,"package") #  "lubridate"
At this point, our data is formatted as a Period object.
We can now transform this Period object to seconds only using the period_to_seconds function of the lubridate package:
my_seconds <- period_to_seconds(my_hms_lubri) # Convert Period to seconds my_seconds # Print seconds #  625 244 80 702
The previous output shows our times in seconds only.
Let’s test the class of our final data:
class(my_seconds) # Check class of data object #  "numeric"
It is numeric!
Video, Further Resources & Summary
Have a look at the following video on my YouTube channel. I’m explaining the R codes of this tutorial in the video.
In addition, you may read the related posts on this homepage.
- Convert Year, Month, Day, Hour, Minutes & Seconds to Date & Time
- Calculate Sum & Mean of Hours, Minutes & Seconds
- Extract Hours, Minutes & Seconds from Date & Time Object
- Convert Character String to Date Object
- R Programming Tutorials
In summary: In this R programming tutorial you have learned how to convert hours, minutes, and seconds into seconds only. Don’t hesitate to let me know in the comments below, if you have additional questions.