You can use the **difftime()** function to calculate the time difference between two dates or datetimes in R.

This function uses the following basic syntax:

**difftime(time1, time2, units="days")
**

where:

**time1, time2**: The two dates or datetimes**units**: The units to use for time difference (default is “days”, but other options include “secs”, “mins”, “hours”, and “weeks”)

The following examples show how to use the **difftime()** function in different scenarios.

**Example 1: Use difftime() to Calculate Time Difference in Various Units**

The following code shows how to use the **difftime()** function to calculate the time difference between two datetimes using various units:

**#define two datetimes
first <- "2022-08-20 08:15:22"
second <- "2022-01-01 20:04:48"
#calculate time difference in days
difftime(first, second)
Time difference of 230.5073 days
#calculate time difference in seconds
difftime(first, second, units="secs")
Time difference of 19915834 secs
#calculate time difference in minutes
difftime(first, second, units="mins")
Time difference of 331930.6 mins
#calculate time difference in hours
difftime(first, second, units="hours")
Time difference of 5532.176 hours
#calculate time difference in weeks
difftime(first, second, units="weeks")
Time difference of 32.92962 weeks
**

By using the **units** argument, we can calculate the time difference between the two datetimes in different units.

**Example 2: Calculate Time Difference in HH:MM:SS Format**

We can also use the **as_hms()** function from the **hms** library to calculate the time difference between two datetimes, formatted as HH:MM:SS.

**library(hms)
#define two datetimes
first <- "2022-01-01 20:15:22"
second <- "2022-01-01 08:04:48"
#calculate difference between datetimes in hours, minutes, seconds
as_hms(difftime(first, second))
12:10:34**

The output shows the time difference between the two datetimes, formatted in terms of hours, minutes, and seconds.

In this scenario, the difference between the two times is **12** hours, **10** minutes, and **34** seconds.

**Additional Resources**

The following tutorials explain how to perform other common tasks in R:

How to Convert UNIX Timestamp to Date in R

How to Convert a Character to a Timestamp in R

How to Extract Year from Date in R

How to Sort a Data Frame by Date in R