Get difference between two timestamps in R by hours, minutes, Seconds and milliseconds

In Order to get difference between two timestamps in R by hours, minutes, seconds and milliseconds we will be using difftime() function. Let’s see how to

  • Get difference between two timestamp in R by hours with an example.
  • Get difference between two timestamp in R by minutes with an example.
  • Get difference between two timestamp in R by seconds with an example.
  • Get difference between two timestamp in R by milliseconds with an example.

Let’s first create the dataframe.

### Create Data Frame

df1 = data.frame (
  Name =c('Annie','Catherine','Teresa','Peterson','Richard','joe'),
  Login_time = as.POSIXct(c('2018-06-03 19:40:00','2018-06-03 11:30:30','2018-06-03 2:04:13','2018-06-03 16:44:43','2018-06-03 7:14:43','2018-06-03 17:12:41')),
  Logout_time = as.POSIXct(c('2018-06-03 21:40:34','2018-06-03 12:40:10','2018-06-03 3:44:23','2018-06-03 17:34:13','2018-06-03 9:34:23','2018-06-03 18:32:41')))
df1

dataframe df1 will be

Get difference between two timestamp in R by minutes with an example 1

 

Get difference between two timestamp in R by hours with an example:

Difference between two timestamp in hours can be calculated using difftime function with argument units = “hours” as shown below

#difference in hours
df1$diff_in_hours = as.numeric(difftime(df1$Logout_time, df1$Login_time, units ="hours"))
df1

so the resultant data frame will be

Get difference between two timestamp in R by minutes with an example 2

 

Get difference between two timestamp in R by minutes with an example:

Difference between two timestamp in minutes can be calculated using difftime function with argument units = “mins”  as shown below

#difference in minutes

df1$diff_in_mins = as.numeric(difftime(df1$Logout_time, df1$Login_time, units ="mins"))
df1

so the resultant data frame will be

Get difference between two timestamp in R by minutes with an example 3

 

Get difference between two timestamp in R by seconds with an example:

Difference between two timestamp in seconds can be calculated using difftime function with argument units = “secs”  as shown below

#difference in seconds

df1$diff_in_secs = as.numeric(difftime(df1$Logout_time, df1$Login_time, units ="secs"))
df1

So the resultant data frame will be

Get difference between two timestamp in R by minutes with an example 4

 

Get difference between two timestamp in R by milliseconds with an example:

Difference between two timestamp in milliseconds can be calculated using difftime function with argument units = “secs”   and it is multiplied by 1000 as shown below

#difference in seconds

df1$ diff_in_milliseconds= as.numeric(difftime(df1$Logout_time, df1$Login_time, units ="secs")) *1000
df1

So the resultant data frame will be

Get difference between two timestamp in R by minutes with an example 5