What is the difftime() function in R?
Overview
The difftime() function in R computes the difference between two objects of date or time.
Syntax
difftime(time1, time2, tz,units = c("auto", "secs", "mins", "hours","days", "weeks"))
Syntax for the difftime() function
Parameter value
The difftime() function takes the following parameter values:
time1,time2: These are the date/time objects.tz: This is an optional parameter that specifies the timezone for conversion. It is specially used forPOSIXltobjects.units: This is a character string that represents the unit in which the results are desired, i.e., the time difference in minutes, hours, days, etc. Abbreviations like "m," "h," or "d" can also be passed.
Return value
This function returns the difference between two objects of data/time in the specified unit.
Example
# Creating date-time objectstime1 <- "2021-02-13 19:09:24"time2 <- "2021-02-12 19:09:24"# Calling the difftime() function where our result should be in unit hoursdifftime(time1, time2, units="hours")
Explanation
- Lines 2 to 3: We create date-time objects
time1andtime2. - Line 6: We implement the
difftime()function on the date-time objects, represent our result inhours, and print the time difference.