How to convert time difference into minutes in R? - r

I have the following program:
timeStart<-Sys.time()
timeEnd<-Sys.time()
difference<-timeEnd-timeStart
anyVector<-c(difference)
at the end I need to put that data into a vector, the problem that I have is than when the difference is in seconds the value is like:
4.46809 seconds
and when it passes some minutes the values is like:
2.344445 minutes
I would like that the answer is converted to minutes in any case, but when I do something like this:
anyVector<-c(difference/60)
for the case that the value of the difference is in seconds work fine, but it will also transform the data when is in minutes giving me an incorrect number.
So, how I can convert to minutes only when the answer is in seconds and not where is in minutes already?

You can do it with the difftime function from base R:
timeStart<-Sys.time()
timeEnd<-Sys.time()
difference <- difftime(timeEnd, timeStart, units='mins')
Output
> difference
Time difference of 0.1424748 mins
You just specify the units argument and set it to mins and the output will always be in minutes.

Related

lubridate - get hours and minutes from decimal hours

I have decimal hours in format 245.85 equalling to 245:51:00 in [hh]:mm:ss format.
I want to transform the decimal hours to hh:mm format, but how do I do it?
the original calculation that renders 245.85 is:
library(lubridate)
time_length(hm("7 27")*33,unit = "hours")
what I want is 245:51 or 245:51:00
If I use as.period I get days too - like in:
as.period(dhours(time_length(hm("7 27")*33,"hours")))
[1] "10d 5H 51M 0S"
and for background - my aim is to multiply hours and minutes (e.g. 7:27) by an arbitrary integer (e.g. 33) and get result back in hh:mm format - avoiding days (as in as.period example above). Say if a piece of work takes 7 hours and 27 minutes and we give me 33 pieces of such work to do per year, it should take me about this many work hours (and minutes) to do.
If it's really only the H:M:S format that gives you trouble, try
library(hms)
hms(hours=245.85)
which yields 245:51:00

how would you calculate the number of seconds since epoch in eiffel for a DATE_TIME object

how would you calculate the number of seconds since epoch in eiffel for a DATE_TIME object?
Assuming variable t is of type DATE_TIME (in UTC), the code to get the corresponding number of seconds since the epoch is
t.definite_duration (create {DATE_TIME}.make_from_epoch (0)).seconds_count
Note. If the calculation is performed rather often, it might be more efficient to create an object epoch of type DATE_TIME with create epoch.make_from_epoch (0) in advance and to use it in the calculation instead:
t.definite_duration (epoch).seconds_count
This seems to work:
make
-- Execute the example
local
l_date:DATE_TIME
l_seconds:INTEGER_64
do
create l_date.make_now
l_seconds := l_date.relative_duration (create {DATE_TIME}.make_from_epoch (0)).seconds_count
print("The number of seconds: " + l_seconds.out + "%N")
end

Changing Time To A Comparable Function In R

I have a dataset in .csv, and I have added in a column on my own in the csv that takes the total time taken for a task to be completed. There are two other columns that consists of the start time and the end time, and that is where I calculated the total time taken column from. The format of the start time and end time columns are in the datetime format 5/7/2018 16:13 while the format of the total time taken column is 0:08:20(H:MM:SS).
I understand that for datetime, it is possible to use the functions as.Date or as.POSIXlt to change the variable type from a factor to that of date. Is there a function that I can convert my total time taken column to (from that of factor) so that I can use it to plot scatterplots/plots in general? I tried as.numeric but the numbers that come out are gibberish and do not correspond to the original time.
If you want to plot the total time taken for each row, then I would suggest just plotting that difference as seconds. Here is a code snippet which shows how you can convert your start or end date into a numerical value:
start <- "5/7/2018 16:13"
start_date <- as.POSIXct(start, format="%d/%m/%Y %H:%M")
as.numeric(start_date)
[1] 1530799980
The above is a UNIX timestamp, which is number of seconds since the epoch (January 1, 1970). But, since you want a difference between start and end times, this detail does not really matter for you, and the difference you get should be valid.
If you want to use minutes, hours, or some other time unit, then you can easily convert.

Get current time in milliseconds

I am trying to do an API call which requires a time in milliseconds. I am pretty new in R and been Googling for hours to achieve something like what In Java would be:
System.currentTimeMillis();
Only thing i see is stuff like
Sys.Date() and Sys.time
which returns a formatted date instead of time in millis.
I hope someone can give me a oneliner which solves my problem.
Sys.time does not return a "formatted time". It returns a POSIXct classed object, which is the number of seconds since the Unix epoch. Of course, when you print that object, it returns a formatted time. But how something prints is not what it is.
To get the current time in milliseconds, you just need to convert the output of Sys.time to numeric, and multiply by 1000.
R> print(as.numeric(Sys.time())*1000, digits=15)
[1] 1476538955719.77
Depending on the API call you want to make, you might need to remove the fractional milliseconds.
No need for setting the global variable digits.secs.
See strptime for details.
# Print milliseconds of current time
# See ?strptime for details, specifically
# the formatting option %OSn, where 0 <= n <= 6
as.numeric(format(Sys.time(), "%OS3")) * 1000
To get current epoch time (in second):
as.numeric(Sys.time())
If you want to get the time difference (for computing duration for example), just subtract Sys.time() directly and you will get nicely formatted string:
currentTs <- Sys.time()
# about five seconds later
elapsed <- Sys.time() - currentTs
print(elapsed) # Time difference of 4.926194 secs

Set units of difference between datetime objects

The diff command returns the differences between dates in a vector of dates in the R date format. I'd like to control the units that are returned, but it seems like they are automatically determined, with no way to control it w/ an argument. Here's an example:
> t = Sys.time()
> diff(c(t, t + 1))
Time difference of 1 secs
And yet:
> diff(c(t, t+10000))
Time difference of 1.157407 days
The "time delta" object has a units attribute, but it seems silly to write a bunch of conditionals to coerce everything into days, seconds etc.
I'm not sure what you mean by "a bunch of conditionals," just change the units manually.
> t = Sys.time()
> a <- diff(c(t,t+1))
> b <- diff(c(t, t+10000))
> units(a) <- "mins"
> units(b) <- "mins"
> a
Time difference of 0.01666667 mins
> b
Time difference of 166.6667 mins
See ?difftime. If you only need to use diff to get the difference between two times (rather than a longer vector), then, as Dirk suggests, use the difftime function with the units parameter.
A POSIXct type (which you created by calling Sys.time()) always use fractional seconds since the epoch.
The difftime() functions merely formats this differently for your reading pleasure. If you actually specify the format, you get what you specified:
R> difftime(t+ 10000,t,unit="secs")
Time difference of 10000 secs
R> difftime(t+ 10000,t,unit="days")
Time difference of 0.115741 days
R>
I think you need difftime in which you can specify the desired units. See:
> difftime(Sys.time(), Sys.time()+10000)
Time difference of -2.777778 hours
> difftime(Sys.time(), Sys.time()+10000, units="secs")
Time difference of -10000 secs
Not sure how precise you care to be, but you can get very specific about date-times with the lubridate package. A wonky thing about time units is that their length depends on when they occur because of leap seconds, leap days, and other conventions.
After you load lubridate, subtracting date times automatically creates a time interval object.
library(lubridate)
int <- Sys.time() - (Sys.time() + 10000)
You can then change it to a duration, which measures the exact length of time. Durations display in seconds because seconds are the only unit that has a consistent length. If you want your answer in a specific unit, just divide by a duration object that has the length of one of those units.
as.duration(int)
int / dseconds(1)
int / ddays(1)
int / dminutes(5) #to use "5 minutes" as a unit
Or you could just change the int to a period. Unlike durations, periods don't have an exact and consistent length. But they faithfully map clock times. You can do math by adding and subtracting both periods and durations to date-times.
as.period(int)
Sys.time() + dseconds(5) + dhours(2) - ddays(1)
Sys.time() + hours(2) + months(5) - weeks(1) #these are periods
If yon need to use the diff() function (e.g. as I do in within a ddply function), you can also turn the input data into numeric format to always receive differences in seconds like this:
> t = Sys.time()
> diff(as.numeric(c(t, t+1)))
[1] 1
> diff(as.numeric(c(t, t+10000)))
[1] 10000
From that point on you can use the diff seconds to calculate differences in other units.

Resources