r - 以小数秒为单位的R中的日期时间转换

标签 r date time

如何转换字符串

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


变成一个数字?
尝试了几种方法-但没有一种有效。

最佳答案

基本思想是将字符串转换为有效的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"

关于r - 以小数秒为单位的R中的日期时间转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15906584/

相关文章:

r - 从分类变量创建新的虚拟变量列

java - 以日期格式而不是字符串获取格式化日期

javascript - mui-datatables 中的日期排序不正确

c - 向 stat() 添加几秒的偏移量

java - 如何在解析时存储日期和时间

r - 如何自定义或显示模式栏?

r - 返回R中行中三个最高值的函数

python - 如何避免 Pandas DataFrame 中过多的 lambda 函数分配和应用方法链

linux - Bash 验证日期

python - 在Python中查找本周的星期一