amisos55
amisos55

Reputation: 1979

r Converting from milliseconds to Hours and Minutes

I have a set of times in milliseconds that I want to convert to hh: mm. An example dataset would be:

data <- c(5936500, 5438500, 3845400, 7439900, 5480200, 6903900)

I get this with manual calculation but it does not provide me the correct value for the minutes.

> data/1000/60/60

[1] 1.649028 1.510694 1.068167 2.066639 1.522278 1.917750

I tried this

format(as.POSIXct(Sys.Date())+data, "%H:%M")
[1] "12:01" "17:41" "07:10" "21:38" "05:16" "16:45"

but that is not even close. Any thoughts on that?

Thanks!

Upvotes: 1

Views: 1477

Answers (2)

jay.sf
jay.sf

Reputation: 73692

The zero point we can get by doing:

strftime(as.POSIXlt.numeric(0, format="%OS", origin="1970-01-01") - 7200, format="%R")
# [1] "00:00"

Accordingly:

t.adj <- 0
res <- strftime(as.POSIXlt.numeric(v/1000, format="%OS", origin="1970-01-01") - t.adj*3600, 
                format="%R", tz="GMT")
res
# [1] "01:38" "01:30" "01:04" "02:03" "01:31" "01:55"
class(res)
# [1] "character"

The date doesn't matter, since:

class(res)
# [1] "character"

Note, that this solution might depend on your Sys.getlocale("LC_TIME"). In the solution above there is an optional hour adjustment t.adj*, however in my personal locale it's set to zero to yield the right values.

Data

v <- c(5936500, 5438500, 3845400, 7439900, 5480200, 6903900)

*To automate the localization you may want to look into the answers to this question.

Upvotes: 1

d.b
d.b

Reputation: 32558

hrs = data/(60 * 60 * 1000)
mins = (hrs %% 1) * 60
secs = (mins %% 1) * 60
paste(trunc(hrs), trunc(mins), round(secs, 2), sep = ":")
#[1] "1:38:56.5" "1:30:38.5" "1:4:5.4"   "2:3:59.9"  "1:31:20.2" "1:55:3.9" 

Also,

library(lubridate)
seconds_to_period(data/1000)
#[1] "1H 38M 56.5S"             "1H 30M 38.5S"             "1H 4M 5.40000000000009S" 
#[4] "2H 3M 59.8999999999996S"  "1H 31M 20.1999999999998S" "1H 55M 3.89999999999964S"

Upvotes: 2

Related Questions