Kaushal
Kaushal

Reputation: 71

finding timestamp difference for a day in R

I have data in the interval of 15 minutes and i need to find the time difference between the next record and current record using R but i am not able to do. Can some help here?

    TIMESTAMP         ID  timediff
07/29/2014 10:15 AM 189252  0:15
07/29/2014 10:45 AM 189252  0:30
07/29/2014 11:00 AM 189252  0:15
07/29/2014 11:15 AM 189252  0:15
07/29/2014 11:30 AM 189252  0:15
07/29/2014 11:45 AM 189252  0:15
07/29/2014 12:00 PM 189252  0:15
07/29/2014 12:15 PM 189252  0:15
07/29/2014 12:30 PM 189252  0:15
07/29/2014 01:00 PM 189252  0:30
07/29/2014 01:15 PM 189252  0:15
07/29/2014 01:30 PM 189252  0:15
07/29/2014 01:45 PM 189252  0:15

Upvotes: 0

Views: 95

Answers (2)

keegan
keegan

Reputation: 2992

You can use diff if the TIMESTAMP entries are Date objects - use as.Date() to makes sure.

now1<-Sys.time()
now2<-Sys.time()
now3<-Sys.time()
now4<-Sys.time()

df<-data.frame(TIMESTAMP=c(now1,now2,now3,now4))
df$differences<-c(NA,diff(df$TIMESTAMP))

Upvotes: 0

Stephan Kolassa
Stephan Kolassa

Reputation: 8267

This is straightforward as long as your data are in an appropriate date-time format:

> foo <- as.POSIXct(c("07/29/2014 10:15","07/29/2014 10:45"),
  format="%m/%d/%Y %H:%M")
> foo
[1] "2014-07-29 10:15:00 CEST" "2014-07-29 10:45:00 CEST"
> diff(foo)
Time difference of 30 mins

Look at ?as.POSIXct and ?strptime.

Upvotes: 1

Related Questions