How to Extract time from timestamp in R ?
In this article, we are going to see how to extract time from timestamp in the R Programming language.
Method 1: Using POSIXct class in R
We can store a date variable in the form of a string variable, and then convert it to a general format timestamp. POSIXct method can be used which converts a date-time string variable into a POSIXct class. as.POSIXct method is used which stores both the date and time along with an associated time zone in R. The POSIXlt class maintains the record of the hour, minute, second, day, month, and year separately. POSIXct class saves the date and time in seconds where in the number of seconds begin at 1 January 1970. This method is used for storage and computation. The format() method can be used to then extract the timestamp from the datetime object.
The format() method has the following syntax :
format(date, format =) ,
where the first parameter illustrates the date and second the specific format specifier
 "Original TimeStamp: "  "2020-01-08 12:48:00 UTC"  "Extraction of time: "  "12:48:00"
Method 2: Using Lubridate package in R
Lubridate package in R is used to store and modify the date formats. It has a large variety of parse functions available, which allow the access of dates and various formats with great simplicity. dmy_hms() method in this package is the most common method, used to store the dates in the standard format (data-month-year-hour-minute-second). In case the time zone(tz) is not specified, the standard UTC zone is used for computations. Specific information can be extracted from this object, without affecting the original datetime object. The format() method is used to extract time from this lubridate datetime object.
The dmy_hms() method has the following syntax :
which returns the date in complete time stamp format.
 "Original TimeStamp: "  "2020-01-08 11:18:56 UTC"  "Extraction of time: "  "11:18:56"
Method 3: Using hms package in R
hms package in R can also be used to perform access, storage, and perform arithmetic operations on date-time objects. The package can first be installed into the environment using the command :
The package can then be included to provide methods to work with date-time object manipulations. The library provides a function as_hms(date) which is used to directly access the time stamp from the date-time object. hms stands for hour minutes and seconds. The string type date needs to be converted to a standard POSIXct format first, in order to apply this method.
The as_hms(date) method takes as input the complete datetime object and extracts the timestamp from it.
 "Original TimeStamp: "  "2020-01-08 12:15:38 IST"  "Extraction of time: "  12:15:38