Reputation: 135
I have a data frame with two text columns which are essentially time-stamps columns namely BEFORE and AFTER and the format is 12/29/2016 4:29:00 PM. I want to compare if the gap between the BEFORE and AFTER time for each row is more than 5 minutes or not. Which package in R will allow subtraction between time stamp?
Upvotes: 1
Views: 57
Reputation: 121618
No need for extra packages, using base R you can achieve the date time comparison.
First coerce your character to a valid date time structure. Here I am using POSIXct
:
d1= as.POSIXct("12/29/2016 4:29:00 PM",format="%m/%d/%Y %H:%M:%S")
d2= as.POSIXct("12/30/2016 5:29:00 PM",format="%m/%d/%Y %H:%M:%S")
Then to get the difference in minutes you can use difftime
:
difftime(d1,d2,units="mins")
Note the all those functions are vectorized So the same code will work with vectors.
to take care of PM/AM we should add %p to the format that should be used in conjonction with %I
not %H
:
d1= as.POSIXct("12/28/2016 11:53:00 AM",
format="%m/%d/%Y %I:%M:%S %p")
d2= as.POSIXct("12/28/2016 12:03:00 PM",
format="%m/%d/%Y %I:%M:%S %p")
difftime(d2,d1,units="mins")
## Time difference of 10 mins
for more help about date/time format you can read ?strptime
.
Upvotes: 1