Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Find time difference in seconds for YYYY-MM-DD HH:MM:SS.MMM format

I'm trying to subtract 2 character vectors containing date time information in the following format:

> dput(train2)

structure(list(time2 = c("2011-09-01 23:44:52.533", "2011-09-05 12:25:37.42", 
"2011-08-24 12:56:58.91", "2011-10-25 07:18:14.722", "2011-10-25 07:19:51.697"
), time3 = c("2011-09-01 23:43:59.752", "2011-09-05 12:25:01.187", 
"2011-08-24 12:55:13.012", "2011-10-25 07:16:51.759", "2011-10-25 07:16:51.759"
)), .Names = c("time2", "time3"), row.names = c(NA, 5L), class = "data.frame")

I've hunted around and played with zoo, as.Date, as.POSIXct, etc. to try and find the correct code to subtract 2 datetime objects and get an answer in seconds but without luck.

I'd appreciate any suggestions.

like image 804
screechOwl Avatar asked Sep 26 '12 22:09

screechOwl


People also ask

How do I calculate time difference between seconds in R?

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”)

How do you find the difference in time with seconds?

Total seconds between times: To get the total seconds between two times, you multiply the time difference by 86400, which is the number of seconds in one day (24 hours * 60 minutes * 60 seconds = 86400).

How do I subtract two timestamps in R?

The difftime() method in R is used to compute the difference in the timestamps given. It is used to return an object of the class difftime itself accompanied by units attribute.

How do I change the date format in R?

To format = , provide a character string (in quotes) that represents the current date format using the special “strptime” abbreviations below. For example, if your character dates are currently in the format “DD/MM/YYYY”, like “24/04/1968”, then you would use format = "%d/%m/%Y" to convert the values into dates.


1 Answers

>  x1<-"2013-03-03 23:26:46.315" 
>  x2<-"2013-03-03 23:31:53.091"
>  x1 <- strptime(x1, "%Y-%m-%d %H:%M:%OS")
>  x2 <- strptime(x2, "%Y-%m-%d %H:%M:%OS")
> x1
[1] "2013-03-03 23:26:46"
> x2
[1] "2013-03-03 23:31:53"

I followed the answer of @Dirk Eddelbuettel, but I am losing precision. How can I force R to not be cuting parts of second?

Thankfully (man of strptime) I answered my question myself:

op <- options(digits.secs = 3)

After applying this setting the precision will be used.

http://stat.ethz.ch/R-manual/R-devel/library/base/html/strptime.html

The belowe may be useful if you would like to get difference in seconds, but get in minutes:

> as.numeric(x2-x1,units="secs")
[1] 306.776
like image 104
andilabs Avatar answered Sep 19 '22 14:09

andilabs