How to Extract Time from Datetime in R ?
Last Updated :
30 Jun, 2021
In this article, we are going to extract time from Datetime in R programming language using lubridate() function and format() function.
Note: datetime is in the format of time and date (YYYY/MM/DD HH:MM:SS) i.e. Year:month:day Hours:Minute:Seconds
Where,
- Year:month:day comes under date
- Hours:Minute:Seconds comes under time
Method 1: Using format() function
We are going to extract only time and for that create a variable and assign a timestamp to it. Then, extract time from the timestamp. We can do this by using as.POSIXct() function. To get a particular time hour format we can use format() function
Syntax:
format(as.POSIXct(data), format = “%H:%M”)
Parameter:
- as.POSIXct() is used to extract time from the time stamp
- format is used to get the time format. Ex : hours:Minutes and seconds
- format = “%H:%M:%S” (To get hours: minutes :seconds)
- format = “%H:%M” (To get hours: minutes )
- format = “%H” (To get hours)
- data is the time stamp
Example 1:
R
data = "2021/05/25 12:34:25"
print ( paste (
"Hours : " , format ( as.POSIXct (data), format = "%H" )))
print ( paste (
"Minutes : " , format ( as.POSIXct (data), format = "%M" )))
print ( paste (
"Seconds : " , format ( as.POSIXct (data), format = "%S" )))
print ( paste (
"Hours and Minutes : " , format ( as.POSIXct (data), format = "%H:%M" )))
print ( paste (
"Time : " , format ( as.POSIXct (data), format = "%H:%M:%S" )))
|
Output:
Example 2:
R
data = c ( "2021/05/25 12:34:25" , "2022/05/25 11:39:25" ,
"2011/05/25 08:31:25" , "2013/04/13 1:34:25" ,
"2018/05/25 12:34:25" )
print ( paste ( "Time : " , format (
as.POSIXct (data), format = "%H:%M:%S" )))
|
Output:
Method 2 : Using lubridate() function
lubridate() package is used to return the time from the datetime individually. It will return hour, minute, and second separately.
- To get hour from the datetime we will use hour command
Syntax:
hour(datetime)
Returns the time in hours
- To get minutes from the datetime we will use minute command
Syntax:
minute(datetime)
Returns the time in minutes
- To get seconds from the datetime we will use second command
Syntax:
second(datetime)
Returns the time in seconds
Example 1:
R
library ( 'lubridate' )
data = "2021/05/25 12:34:25"
hour (data)
minute (data)
second (data)
|
Output:
Share your thoughts in the comments
Please Login to comment...