How to Get a Difference Between 2 Date (or Time) Values.

Suppose you have user data in a data frame. Each row represents a user, and each row also has the first and last date/time of access in POSIXct data type.

Now, you want to see the difference between the first and last date/time for each user. Here is how.

From the column header menu of ‘last’ column, choose ‘Create Calculation (mutate)’.

In Calculation Editor, subtract ‘first’ from ‘last’ by last - first. Set the ‘diff’ for a new column name.

Then, you will see a new column ‘diff’ with number values. Those numbers represent differences in seconds if you compare date/time data (POSIXct data) or differences in days if you compare date data.

You can change the unit of the differences from the column header menu. You can open the column header menu of the ‘diff’ column, select ‘Change Data Type’ and choose ‘Convert to Numeric’. Then you will see a list of units. You can pick the one you like.

Show Differences in a Human-Readable Format

Sometimes you want to see the differences in a more human-readable format like ‘Day Hour Min Sec’. You can use a string representation of ‘period’ object to do it. Here is how.

From the column header menu of ‘diff’ column, choose ‘Create Calculation (mutate)’.

Put as.character(as.period(diff)) in Calculation Editor. Set the ‘period’ for a new column name.

Then, you will see a new column ‘period’ with differences in a human-readable format.