Parse time and convert to minutes

Viewed 83

Data looks like this.

data$arrival_time: int  1245 1345 1805 1950 710 755 2115 2215 615 730 ...
data$real_time   : int  1256 1423 1859 2105 712 1009 2139 2344 542 946 ...

For example, 1245 means 12:45 and 1345 means 13:45.

And I just want to convert 12:45 to 765 and 13:45 to 825, so it can be converted format(hour:minutes) to minutes. (cf. 1260+450=765 and 1360+45=825)

How can I convert time to minutes?

3 Answers

Modular arithmetic is your friend here. Two helpful R operators:

  • %/% does integer division, e.g. 5 %/% 2 is 2 and 38 %/% 3 is 12
  • %% is the modulo/remainder opeartor, e.g. 5 %% 2 is 1 and 38 %% 3 is 2

For positive integers where m<n, we always have n = m*(n %/% m) + n %% m.

We can use that to help by recognizing the "hour" part of your input is given by x %/% 100, while the "minute" is given by x %% 100, so your answer is:

60 * (x %/% 100) + ( x %% 100 )
#    ^ hours   ^   ^ minutes  ^

You may use floor and %%.

v <- c(1245, 1345, 1805, 1950, 710, 755, 2115, 2215, 615, 730, 000)

floor(v/100)*60 + v %% 100
# [1]  765  825 1085 1190  430  475 1275 1335  375  450    0

You can try a mathematical approach, i.e.

x <- c(1245, 1345, 710, 2115, 542, 946)

(floor(x / 100) * 60) + (x - round(x, -2))
#[1]  765  825  430 1275  342  586
Related