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"

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

Now, we can extract the hours…

hour(x)                           # Extract hour
# 3


minute(x)                         # Extract minute
# 22

…and seconds…

second(x)                         # Extract second
# 56

…from our date and time character string.

Note that the output values of the previous R code have the numeric class. You may convert these outputs to other data types such as the character class or to the factor class.


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:


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 the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.