How to compare time in R?
R programming Language supports both date and DateTime objects using various different formats and specifiers. The built-in framework as.Date function is responsible for the handling of dates alone, the library chron in R Programming handles both dates and times, without any support for time zones; whereas the POSIXct and POSIXlt classes provides the support for handling datetime objects as well as timezones. Easy conversion of date time objects can be performed to other date related objects.
A date string can be first converted to a POSIXct objects and then basic arithmetic can be performed on it easily. POSIXct objects ease the process of mathematical operations, since they rely on seconds as the major unit of time management. The dates are converted to standard time zone, UTC. A string type date object can be converted to POSIXct object, using the as.POSIXct(date) method in R. Since, the dates are stored on seconds, the subtraction can be performed by first converting the hours and minutes to the units of seconds too.
1 hour = 1 * 60 * 60 seconds
1 min = 1 * 60 seconds
Method 1 : Using logical operators
POSIXct dates can be compared using the logical operators to compare dates. Logical operators are applied in between the different argument dates and a boolean TRUE or FALSE value is returned based on the output.
 "Time 1"  "2021-05-18 08:32:07 UTC"  "Time 2"  "2021-05-18 08:32:08 UTC"  "Time1 smaller"
Method 2 : Using comparison operators
- Using difftime() method
The difftime() method in R language is used to compute the difference in the timestamps given. It is used to return an object of the class difftime itself accompanied by a units attribute. “difftime” objects support only limited arithmetic operations upon them, that is, they can be added or subtracted, and multiplied or divided by a numeric vector. The result returned by this method is based on the first parameter time stamp value subtracted by second parameter, that is time1-time2. The result is positive in case the time1 is larger than time2, 0 if the two time frames are equal and negative for the remaining case.
Syntax: difftime(time1, time2, tz,units = c(“auto”, “secs”, “mins”, “hours”,”days”, “weeks”))
- time1 and time2 – the datetime objects or numeric vectors
- tz – time zone (optional)
- units – the specification of units to perform arithmetic on
Return type : a difftime object applying the arithmetic on datetime object
 "Time 1"  "2021-05-18 08:35:07 UTC"  "Time 2"  "2021-05-18 08:32:08 UTC"  "Time1 - Time2" Time difference of 0.04972222 hours
- Using ‘-‘ operator
The date objects can be compared using the minus operator to subtract the smaller date from the larger date. The units in which the date is returned is the maximum of the hours, minutes or seconds.
 "Time 1"  "2021-05-18 09:35:07 UTC"  "Time 2"  "2021-05-18 09:35:08 UTC"  "Time2 - Time1" Time difference of 1 secs