In R
I have two strings:
t <- c("2010-01-01 00:01:02", "2010-01-01 00:02:02")
which I convert to POSIX datetimes:
dt <- as.POSIXct(t)
Taking the difference of the two dt[2] - dt[1]
gives:
Time difference of 1 mins
Cool. But how do I force the time difference to be in, say, seconds?
You can use the difftime() function to calculate the time difference between two dates or datetimes in R. where: time1, time2: The two dates or datetimes. units: The units to use for time difference (default is “days”, but other options include “secs”, “mins”, “hours”, and “weeks”)
R provides several options for dealing with date and date/time data. The builtin as. Date function handles dates (without times); the contributed library chron handles dates and times, but does not control for time zones; and the POSIXct and POSIXlt classes allow for dates and times with control for time zones.
First, there are two internal implementations of date/time: POSIXct , which stores seconds since UNIX epoch (+some other data), and POSIXlt , which stores a list of day, month, year, hour, minute, second, etc. strptime is a function to directly convert character vectors (of a variety of formats) to POSIXlt format.
> difftime(dt[2], dt[1], units="secs")
Time difference of 60 secs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With