How to Extract Time from Datetime in R ?
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
- 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
format(as.POSIXct(data), format = “%H:%M”)
- 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
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
Returns the time in hours
- To get minutes from the datetime we will use minute command
Returns the time in minutes
- To get seconds from the datetime we will use second command
Returns the time in seconds