I want to log the time in R
like I do in Python 3
but I have no idea where to even start. In Python
I would do it this way. How would I do this same thing in R
?
>>> import time
>>> start_time = time.time()
>>> time.time() - start_time
6.0202391147613525
Sys.time
is what you need.
current_time <- Sys.time()
Sys.time() - current_time
#Time difference of 2.900852 secs
However, this has a class of difftime
class(Sys.time() - current_time)
#[1] "difftime"
If you want it as a number for manipulation you can use as.numeric
as.numeric(Sys.time() - current_time)
#[1] 2.900852
The units are not always constant here and you might face issues handling it. So for example, when I now do
Sys.time() - current_time
it gives me
#Time difference of 12.12814 mins
Point here to observe is at first the units were in seconds and now they are in minutes. So this is inconsistent and maybe troublesome when you are using them for some calculation.
To overcome that , as @r2evans mentions in the comment we can set the units by doing
my_diff = Sys.time() - current_time
units(my_diff) <- "secs"
my_diff
#Time difference of 592.8649 secs
So this would always return difference in seconds irrespective of the duration passed.