R中的日期时间转换,小数秒

时间:2013-04-09 15:49:27

标签: r date time

如何转换字符串

t <- c("00:00:0.00", "00:00:0.34")
成了一个数字? 尝试了几种方法 - 但没有一种方法有效..

1 个答案:

答案 0 :(得分:10)

基本思路是将您的字符串转换为有效的POSIX*t对象,然后将其转换为numeric值:

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

请注意,在从数字转换回POSIX*t时,存在可以更改这些对象的打印方式的浮点问题。 (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"