Extract Hours, Minutes & Seconds from Date & Time Object in R (Example)
In this tutorial, I’ll explain how to return only hours, minutes, and seconds from a date/time object in the R programming language.
The tutorial will consist of these content blocks:
With that, let’s do this.
Creation of Exemplifying Data
Consider the following example data:
x <- "2023-08-07 03:22:56" # Create example date & time x # Print example date & time # "2023-08-07 03:22:56" |
x <- "2023-08-07 03:22:56" # Create example date & time x # Print example date & time # "2023-08-07 03:22:56"
The previous output of the RStudio console shows that our example data object contains a single character string showing a date and a time.
Example: Extracting Hour, Minute & Seconds from Date & Time Object Using lubridate Package
The R syntax below explains how to extract time metrics from a character string using the lubridate package.
We first have to install and load the lubridate package, if we want to use the functions that are included in the package:
install.packages("lubridate") # Install lubridate package library("lubridate") # Load lubridate package |
install.packages("lubridate") # Install lubridate package library("lubridate") # Load lubridate package
Now, we can extract the hours…
hour(x) # Extract hour # 3 |
hour(x) # Extract hour # 3
…minutes…
minute(x) # Extract minute # 22 |
minute(x) # Extract minute # 22
…and seconds…
second(x) # Extract second # 56 |
second(x) # Extract second # 56
…from our date and time character string.
Video & Further Resources
Some time ago I have released a video on my YouTube channel, which illustrates the examples of this tutorial. You can find the video below.
The YouTube video will be added soon.
Furthermore, you might have a look at the other articles of my website:
- Convert Date to Numeric Time Object
- Extract Day from Date
- Extract Month from Date
- Extract Year from Date
- R Programming Tutorials
You learned on this page how to get hours, minutes, and seconds in R programming. Let me know in the comments section, if you have additional questions.
Subscribe to my free statistics newsletter: