How to convert a chron object to a numerical object of seconds since an origin in R

1.2k Views Asked by At

I have a chron object like this:

 t <- as.chron("06/01/13 01:00:00", "%m/%d/%y %H:%M:%S") 

and I want to convert it to seconds from origin, where the origin is:

 or <- "06/01/13 00:00:00"

so what I want is that the object t become:

 t <- 3600

Thank you very much Giulia

1

There are 1 best solutions below

3
On BEST ANSWER

Just use difftime():

R> library(chron)
R>  t <- as.chron("06/01/13 01:00:00", "%m/%d/%y %H:%M:%S") 
R> or <- as.chron("06/01/13 00:00:00", "%m/%d/%y %H:%M:%S") 
R> difftime(t, or)
Time difference of 1 hours
R> 

or in the units you want:

R> difftime(t, or, unit="secs")
Time difference of 3600 secs
R> as.numeric(difftime(t, or, unit="secs"))
[1] 3600
R> 

As an aside, you probably want to use POSIXct instead of chron which difftime() converts to for you anyway. See help(DateTimeClasses).