ragesz ragesz - 1 year ago 116
R Question

R - convert timestamp (int) to time interval

I have some integers (timestamps) and I want to convert them into time intervals (time deltas). How can I do that in R?

Something like this:

strptime(37998530.34, format="%d %H:%M")

This R code returns with error:

difftime(37998530.34, 0)

In Python I can use this code:

datetime.timedelta(0, 37998530.34)

And the result is:

datetime.timedelta(439, 68930, 340000)
439 days, 19:08:50.340000

Thank you!

Answer Source

In R you need to specify the origin for the date conversion. Assuming your value is the number of seconds use this function:

as.POSIXlt(37998530.34, origin="1970-01-01")
#[1] "1971-03-16 14:08:50 EST"

as.POSIXlt function also has an option to specify the desired timezone (tz= )

The following code:

difftime(as.POSIXlt(37998530.34, origin="1970-01-01"), as.POSIXlt(0, origin="1970-01-01"), units=c('days'))

has the result:

Time difference of 439.8 days
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download