Subtract time in r, forcing unit of results to minutes

242 views Asked by At

I successfully subtracted two POSIXct cols of df1 (below). However, since the time differences are >= 1 hour in all rows, R gives the results in hours. I know that this make sense, but is there a direct way to have it return minutes instead?

df1 <- data.frame(time.stamp1 = c("2015-01-05 15:00:00", "2015-01-05 16:00:00", "2015-01-05 18:00:00", "2015-01-05 19:00:00", "2015-01-05 20:00:00"),
                  time.stamp2 = c("2015-01-05 16:00:00", "2015-01-05 17:00:00", "2015-01-05 20:00:00", "2015-01-05 20:00:00", "2015-01-05 22:00:00"))

df1$time.stamp1 <- as.POSIXct(strptime(df1$time.stamp1, "%Y-%m-%d %H:%M:%S"))                 
df1$time.stamp2 <- as.POSIXct(strptime(df1$time.stamp2, "%Y-%m-%d %H:%M:%S"))                 

df1$time.diff <- df1$time.stamp2 - df1$time.stamp1

Current Result

> df1
          time.stamp1         time.stamp2 time.diff
1 2015-01-05 15:00:00 2015-01-05 16:00:00   1 hours
2 2015-01-05 16:00:00 2015-01-05 17:00:00   1 hours
3 2015-01-05 18:00:00 2015-01-05 20:00:00   2 hours
4 2015-01-05 19:00:00 2015-01-05 20:00:00   1 hours
5 2015-01-05 20:00:00 2015-01-05 22:00:00   2 hours

Desired Result

> df1
          time.stamp1         time.stamp2  time.diff
1 2015-01-05 15:00:00 2015-01-05 16:00:00    60 mins
2 2015-01-05 16:00:00 2015-01-05 17:00:00    60 mins
3 2015-01-05 18:00:00 2015-01-05 20:00:00   120 mins
4 2015-01-05 19:00:00 2015-01-05 20:00:00    60 mins
5 2015-01-05 20:00:00 2015-01-05 22:00:00   120 mins

Many thanks

1

There are 1 answers

0
akrun On BEST ANSWER

You can try with difftime

 df1$time.diff <- with(df1, difftime(time.stamp2, time.stamp1, unit='min'))
 df1
 #         time.stamp1         time.stamp2 time.diff
 #1 2015-01-05 15:00:00 2015-01-05 16:00:00   60 mins
 #2 2015-01-05 16:00:00 2015-01-05 17:00:00   60 mins
 #3 2015-01-05 18:00:00 2015-01-05 20:00:00  120 mins
 #4 2015-01-05 19:00:00 2015-01-05 20:00:00   60 mins
 #5 2015-01-05 20:00:00 2015-01-05 22:00:00  120 mins