Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert hours:minutes:seconds to minutes

I have a vector "Time.Training" in the format hours:minutes:seconds (e.g.

Time.Training <- c("1:00:00", "0:45:00", "0:30:00", "1:30:00")

I would like to convert this into minutes in the format:

Time.Training.Minutes <- c(60, 45, 30, 90)

I'm wondering if someone has a straightforward method of doing this in R.

Many thanks.

Matt

like image 215
Matt Jordan Avatar asked Mar 15 '15 23:03

Matt Jordan


People also ask

How do you convert minutes and seconds to seconds?

How to Convert Minutes to Seconds. To convert a minute measurement to a second measurement, multiply the time by the conversion ratio. The time in seconds is equal to the minutes multiplied by 60.

What is the formula to convert seconds to minutes?

There are 60 seconds in every minute, so converting seconds to minutes is simple. Just divide the number of seconds by 60 to get your answer!

How do you convert seconds to HH mm SS?

To convert seconds to HH:MM:SS :Multiply the seconds by 1000 to get milliseconds.


4 Answers

Using lubridate:

Time.Training<- c("1:00:00", "0:45:00", "0:30:00", "1:30:00")

library(lubridate)
res <- hms(Time.Training)        # format to 'hours:minutes:seconds'
hour(res)*60 + minute(res)       # convert hours to minutes, and add minutes
## [1] 60 45 30 90
like image 52
tospig Avatar answered Oct 23 '22 16:10

tospig


Try this. We basically converting to POSIXlt class first by pasting a real date to the vector using the Sys.Date() function (because there is no hour class in base R) and then using hour and min arguments in order to achieve the output

Res <- as.POSIXlt(paste(Sys.Date(), Time.Training))
Res$hour*60 + Res$min
## [1] 60 45 30 90
like image 20
David Arenburg Avatar answered Oct 23 '22 15:10

David Arenburg


Here are some alternatives:

1) The chron package has a "times" class in which 1 unit is a day and there are 60 * 24 minutes in a day so:

library(chron)
60 * 24 * as.numeric(times(Time.Training))

giving:

[1] 60 45 30 90

1a) Another approach using chron is the following (giving the same answer):

library(chron)

ch <- times(Time.training)
60 * hours(ch) + minutes(ch)

2) Here is an approach using read.table and matrix/vector multiplication. No packages are needed:

c(as.matrix(read.table(text = Time.Training, sep = ":")) %*% c(60, 1, 1/60))

(Using "POSIXlt" is probably the most straight-forward approach without packages but another answer already provides that.)

like image 10
G. Grothendieck Avatar answered Oct 23 '22 14:10

G. Grothendieck


Use as.difftime:

> Time.Training<- c("1:00:00", "0:45:00", "0:30:00", "1:30:00")
> strtoi(as.difftime(Time.Training, format = "%H:%M:%S", units = "mins"))
[1] 60 45 30 90
like image 10
Perceptron Avatar answered Oct 23 '22 16:10

Perceptron