1

I am extracting a time variable from the output of an API request and the output format is as follows.

> a
[1] "2019-09-06T09:03:14.938Z"

The first objective is to derive the difference with Sys.time()

> b<- Sys.time()
> b
[1] "2019-09-06 08:57:08 UTC"

I am having issues to run a basic c = a-b

> c<-a-b
Error in `-.POSIXt`(a, b) : can only subtract from "POSIXt" objects

When trying to convert a into a POSIXT object, I get the following error:

> c<-as.POSIXct.Date(a)
Error in unclass(x) * 86400 : non-numeric argument to binary operator

The second objective would be to make the code wait until the time difference is possitive or zero. Maybe somethimg using sys.sleep?

stevec
  • 41,291
  • 27
  • 223
  • 311
GCGM
  • 901
  • 1
  • 17
  • 38

2 Answers2

3

Use lubridate to convert strings into POSIXct objects, then you can subtract one from the other

library(lubridate)
as_datetime("2019-09-06 08:57:08 UTC") - as_datetime("2019-09-06T09:03:14.938Z")
Time difference of -6.115633 mins

To answer your second question (about waiting between API requests) Sys.sleep() is perfect for this

Sys.sleep(5) # sleeps 5 seconds
stevec
  • 41,291
  • 27
  • 223
  • 311
  • Thank you. It works percfectly but I prefer to use `base` fuctions to avoid installing extra packages in my script! – GCGM Sep 06 '19 at 11:08
2

You need to pass proper format while converting into POSIXct object

a <- as.POSIXct("2019-09-06T09:03:14.938Z", format = "%Y-%m-%dT%T")

and then do

b - a

You can also difftime which has units argument and can accept "secs", "mins", "hours","days", "weeks"

difftime(b, a, units = "mins")

Not exactly clear about the second part of the question however, we can write a while loop to make the code "wait" till time difference is positive or 0.

while(a > Sys.time()) { }
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213