0

I want to subtract a list of time-dates from another in R, to calculate the time in between in minutes. Say I want to subtract 5-7-2017-11:33:31:543 from 5-7-2017-11:36:8:241. As I understand strptime(), I should do the following:

strptime("5-7-2017-11:36:8:241","%d-%m-%Y-%H:%M:%OS") - strptime("5-7-2017-11:33:31:543","%d-%m-%Y-%H:%M:%OS")
op<-options(digits.secs=3)

This gives me the following answer: Time difference of 2.616667 mins

While I am actually looking for 2.37 something.

I can do .616667 * 60, which will give me .37, but I'd rather not for the entire list of data that I have. Any help or explanation is very much appreciated, thanks in advance for your time!

d.b
  • 32,245
  • 6
  • 36
  • 77
David Maij
  • 53
  • 8
  • Some help towards your desired outcome might be found here: http://lubridate.tidyverse.org/articles/lubridate.html#if-anyone-drove-a-time-machine-they-would-crash – DaveRGP Aug 08 '17 at 15:35
  • Additionally I don't recognise the `%OS` formatter you are using, I wonder if it is understood by strptime, I can't see it in the documentation – DaveRGP Aug 08 '17 at 15:39
  • 1
    It would be weirder if the default output was `2.37`. Now you have decimal time and you can format it to whatever form you want. – d.b Aug 08 '17 at 15:39
  • Ideally you would vectorise this arithmetic when you are applying it across a list. If you would like help with that I suggest making a MWE that more closely resembles your implied list of dates and posting it in a new question. – DaveRGP Aug 08 '17 at 15:41
  • 1
    @DaveRGP: Thanks! Btw, I got the %OS (options) from this stackoverflow question: https://stackoverflow.com/questions/2150138/how-to-parse-milliseconds – David Maij Aug 08 '17 at 15:43
  • 1
    @d.b: Fair enough, although at least 2 minutes 37 seconds ... ms... is a real time, whereas 2.61 seems just intuitively strange to me. But i'll just change all the outcomes then! Thanks for thinking along. – David Maij Aug 08 '17 at 15:46

1 Answers1

2

You could use lubridate's as.period:

library(lubridate)

as.period(strptime("5-7-2017-11:36:8:241","%d-%m-%Y-%H:%M:%OS") - strptime("5-7-2017-11:33:31:543","%d-%m-%Y-%H:%M:%OS"))

## "2M 37S"
Oriol Mirosa
  • 2,756
  • 1
  • 13
  • 15