Subtracting time in r

I have a dataset containing two variables for time: EndVisitTime

and BoxTime

. I was doing data per day (so these observations are all in one day):

EndVisitTime<-c("00:00:32",  "00:04:52",  "00:10:01", "00:23:38",  "00:31:28") # class: factor
BoxTime<-as.integer(c("341",  "229", "301",  "810",  "363")) # class integer in seconds
df<-data.frame(Date, EndVisitTime, BoxTime)


I want to calculate StartVisitTime

; that is EndVisitTime - BoxTime


When the visit started on the previous day, I want to get the correct start date ( date = 2014-8-11

). My question is how to subtract BoxTime

(which is in seconds) from EndVisitTime

to get the correct one StartVisitTime

with the correct one StartDate


I tried several options and I can't get any more as they keep adding the current date or the result in 0 to 1 traits which cannot be converted to date and time format.

# This is my most successful attempt
df$EndTime<-strptime(df$EndVisitTime, format="%H:%M:%S")
df$StartVisitTime<-df$EndTime-df$x ### This does not work!


Your help is greatly appreciated and willing !!!


source to share

1 answer

Using POSIXct dates, seconds can be added directly.

Sample data

df<-data.frame(EndVisitTime=c("00:00:32",  "00:04:52",  "00:10:01", "00:23:38",  "00:31:28"),
               BoxTime=c("341",  "229", "301",  "810",  "363"),
               Date = "2014-8-12",stringAsFactor=FALSE)


Combine date and time into one line

df$EndTimeStr<, df[,c("Date", "EndVisitTime")])


Convert to POSIXct time

df$EndTime<-as.POSIXct(df$EndTimeStr,format="%Y-%m-%d %H:%M:%S")


Subtract seconds



Ref How to add / subtract time from POSIXlt while keeping its class in R?



All Articles