Open In App

How to Extract Time from Datetime in R ?

Last Updated : 16 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In R, we can extract the time portion (hours, minutes and seconds) from a datetime string using either the format() function or the lubridate package. These methods allow us to isolate and manipulate just the time portion of a datetime object for further analysis or processing.

1. Using format() Function

We use the format() function along with as.POSIXct() to extract specific parts of time such as hour, minute or second from a datetime string.

Example 1:

We extract hours, minutes, seconds from a single timestamp.

  • data: Input timestamp as a string.
  • as.POSIXct(): Converts the string to datetime format.
  • format(): Extracts formatted components from the datetime.
  • "%H": Hour in 24-hour format.
  • "%M": Minute component.
  • "%S": Second component.
  • "%H:%M": Hour and minute.
  • "%H:%M:%S": Complete time.
R
data <- "2021/05/25 12:34:25"

cat(format(as.POSIXct(data), "%H"), "\n")
cat(format(as.POSIXct(data), "%M"), "\n")
cat(format(as.POSIXct(data), "%S"), "\n")
cat(format(as.POSIXct(data), "%H:%M"), "\n")
cat(format(as.POSIXct(data), "%H:%M:%S"), "\n")

Output:

time
Output

Example 2:

We extract time from a vector of multiple timestamps.

  • data: A vector of date-time strings.
  • as.POSIXct(): Converts the entire vector to POSIXct datetime.
  • format(..., "%H:%M:%S"): Returns time part from each timestamp.
R
data <- c("2021/05/25 12:34:25", "2022/05/25 11:39:25", 
          "2011/05/25 08:31:25", "2013/04/13 01:34:25", 
          "2018/05/25 12:34:25")

cat(format(as.POSIXct(data), "%H:%M:%S"), "\n")

Output:

Time : 12:34:25 11:39:25 08:31:25 01:34:25 12:34:25

2. Using Lubridate Package

We use functions from the lubridate package such as hour(), minute() and second() to directly extract the time components.

Example:

We extract time using lubridate from a single timestamp.

  • library(lubridate): Loads the lubridate package.
  • data: A datetime string.
  • hour(): Extracts the hour.
  • minute(): Extracts the minutes.
  • second(): Extracts the seconds.
R
library(lubridate)

data <- "2021/05/25 12:34:25"

cat(hour(data), "\n")
cat(minute(data), "\n")
cat(second(data), "\n")

Output:

Screenshot-2025-07-16-105431
Output

The output shows that the extracted time components from the datetime string are: 12 hours, 34 minutes and 25 seconds, using lubridate.


Similar Reads