Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date-Time Conversion in R with fractional seconds

Tags:

date

time

r

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..

like image 781
Kay Avatar asked Apr 09 '13 15:04

Kay


People also ask

How do I convert to time in R?

To convert characters to time objects in R, use the strptime() function. To convert time objects to characters in R, use the strftime() function.

What is Posix date format in R?

POSIXct stores date and time in seconds with the number of seconds beginning at 1 January 1970. Negative numbers are used to store dates prior to 1970. Thus, the POSIXct format stores each date and time a single value in units of seconds. Storing the data this way, optimizes use in data.

What is Strptime R?

The strptime function converts characters to time objects and uses the following basic syntax: strptime(character_object, format="%Y-%m-%d") The strftime function converts time objects to characters and uses the following basic syntax: strftime(time_object)


1 Answers

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"
like image 145
Josh O'Brien Avatar answered Sep 30 '22 14:09

Josh O'Brien