Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse time and convert to minutes

Tags:

time

r

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?

like image 370
hyejuryu Avatar asked Jul 09 '20 07:07

hyejuryu


1 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  ^
like image 124
MichaelChirico Avatar answered Sep 28 '22 17:09

MichaelChirico