Kay
Kay

Reputation: 2854

Date-Time Conversion in R with fractional seconds

How to convert the string

t <- c("00:00:0.00", "00:00:0.34")

into a number? tried several approaches - but none of them worked..

Upvotes: 6

Views: 4965

Answers (1)

Josh O&#39;Brien
Josh O&#39;Brien

Reputation: 162321

The basic idea is to convert your character string to a valid POSIX*t object, and then convert that to a numeric value:

## Set a couple of printing options
options(digits = 12)
options(digits.secs = 3)

## Convert from character to POSIXlt to numeric
(a <- strptime(t, format="%H:%M:%OS", tz="GMT"))
# [1] "2013-04-09 00:00:00.00 GMT" "2013-04-09 00:00:00.34 GMT"
(b <- as.numeric(a))
# [1] 1365465600.00 1365465600.34

Note that, when converting back from numeric to POSIX*t, there are floating point issues that can change how those objects are printed. (See here for more discussion of that issue.)

## It _looks_ like you've lost 1/100 second on the second time object
(c <- as.POSIXct(as.numeric(b), origin = "1970-01-01", tz="GMT"))
# [1] "2013-04-09 00:00:00.00 GMT" "2013-04-09 00:00:00.33 GMT"

## Here's a workaround for nicer printing.
as.POSIXct(as.numeric(b+1e-6), origin = "1970-01-01", tz="GMT")
# [1] "2013-04-09 00:00:00.00 GMT" "2013-04-09 00:00:00.34 GMT"

Upvotes: 12

Related Questions