Reputation: 27
I have a running list of 2 variables which include a date and time component. The form of these variables are:
2015-08-29T11:52:04
2015-08-29T11:52:19
I would like to extract the time sections from the variables above (i.e. everything after 'T') and calculate the difference to determine a response time (i.e. 15 seconds in this case)
Looking for some guidance on how to approach this with R. I found a similar solution (Extracting time from a date/time format) but am having difficulty applying the solution to my problem here.
Would appreciate any guidance! Thanks in advance.
Upvotes: 1
Views: 291
Reputation: 887221
We can convert to ITime
and calculate the difference. Based on the OP's post, we need to remove the prefix 'Date' up to 'T' and then use only the time part for calculating the difference
library(data.table)
diff(as.ITime(sub('.*T', '', str1)))
#[1] "00:00:15"
Or another option is to convert the full string to DateTime
with ymd_hms
, convert to ITime
and get the diff
erence
diff(as.ITime(ymd_hms(str1)))
#[1] "00:00:15"
Or with lubridate
library(lubridate)
as.numeric(diff(ymd_hms(str1)))
#[1] 15
Or with difftime
in base R
after converting to Datetime class with as.POSIXct
dtime <- as.POSIXct(str1, format = "%Y-%m-%dT%T")
as.numeric(difftime(dtime[2], dtime[1], unit = 'sec'))
#[1] 15
Or as @Onyambu suggested
diff(strptime(str1,"%FT%T"))
str1 <- c("2015-08-29T11:52:04", "2015-08-29T11:52:19")
Upvotes: 1
Reputation: 389045
In base R, we can convert the time to POSIXct
class and use difftime
to calculate difference between the two specifying units
as required.
time1 <- '2015-08-29T11:52:04'
time2 <- '2015-08-29T11:52:19'
as.numeric(difftime(as.POSIXct(time2, format = '%FT%T'),
as.POSIXct(time1, format = '%FT%T'), units = 'secs'))
#[1] 15
Upvotes: 2