Reputation: 3
I have a time format written in hhmmss.mm, such 225014.09 imported from a table. It's earthquake time. I wanna transform it into 22:50:14(:09?) in R.
I don't know what to do with the milliseconds. It should be the above way. Can anyone help me out? I've searched and searched, but couldn't find the answer.
Upvotes: 0
Views: 2385
Reputation: 368579
There are two general rules for this:
In all seriousness, use a datetime parser of which R has many. But a key here is that you have a time and not yet a date so you cannot yet parse as a datetime.
So do something like this:
R> tstr <- "225014.09"
R> dtstr <- paste("2026-01-01", tstr) # which date does not matter
R> pt <- anytime(dtstr) # now it is parsed
R> pt
[1] "2026-01-01 22:50:14.08 CST"
R> tstr <- "225014.09"
R> dtstr <- paste("2016-01-01", tstr) # which date does not matter
R> pt <- anytime(dtstr) # now it is parsed
R> pt
[1] "2016-01-01 22:50:14.08 CST"
R> hhmmss <- format(pt, "%H:%M:%OS")
R> hhmmss
[1] "22:50:14.089999"
R>
Now we have the preferred hh:mm:ss.ff with fractional seconds -- my default is but you can fine-tune:
R> options(digits.secs=2)
R> hhmmss <- format(pt, "%H:%M:%OS")
R> hhmmss
[1] "22:50:14.08"
R>
The fact that '09' got rounded to '08' is one of those things with floating point math, and cannot be changed by how you parse or format -- it is a limitation of the underlying representation.
Upvotes: 3