Angel
Angel

Reputation: 3

How to convert a time format in hhmmss.mm to normal time in R?

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

Answers (1)

Dirk is no longer here
Dirk is no longer here

Reputation: 368579

There are two general rules for this:

  1. Don't use regular expressions for parsing dates and times
  2. Follow rule 1.

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

Related Questions