Mostafa90
Mostafa90

Reputation: 1706

Data time conversion with milleseconds

I have a dataframe with 4 columns (start, starts.ms, end and end.ms), and my aim is to calculate the duration of each observation using this different variables.

start <- c("25/11/14 16:59:46", "25/11/14 16:59:29  ", "25/11/14 16:58:04")
start.ms <- c(976, 456, 30)
end <- c("25/11/14 17:00:00", "25/11/14 17:00:00", "25/11/14 17:00:00")
end.ms <- c(50, 111, 150)

df <-data.frame(start, start.ms, end, end.ms)

df$start.b <- with(df, paste(start, start.ms, sep = "."))
df$end.b <- with(df, paste(end, end.ms, sep = "."))

And after this, I want to convert the two last columns as data variable and differenciate them to get the duration ! When I use as.Date or strptime, R returns me NA value or nothing ... Thank you in advance.

EDIT : for people who use the "strptime" funtion don't forget to add "options(digits.secs=3)" if you have milleseconds, the output will be in POSIXlt format.

Upvotes: 2

Views: 77

Answers (1)

akrun
akrun

Reputation: 887881

Posting the comment as an answer.

  op <- options(digits.secs=3)
  strptime(df$start.b, format='%d/%m/%y %H:%M:%OS')
  #[1] "2014-11-25 16:59:46.976 EST" "2014-11-25 16:59:29.000 EST"
  #[3] "2014-11-25 16:58:04.300 EST"

Upvotes: 1

Related Questions