以逗号分隔的毫秒数

时间:2017-04-17 21:17:43

标签: r date time milliseconds

我有以下data.frame称为“数据”(它更大但我只是以第一行为例):

  Timestamp Weight Degrees
1 30-09-2016 11:45:00,000 38.19 40.00 
2 01-10-2016 06:19:57,860 39.12 40.00 
3 01-10-2016 06:20:46,393 42.11 41.00

我想将“时间戳”转换为包含毫秒的日期/时间向量。这似乎是一个问题,因为毫秒用逗号分隔。

另外,data.frame有模式“list”,Timestamp有模式“character”,显然不对...

我尝试了data$Timestamp <- as.POSIXct(data$Timestamp,format='%d-%m-%Y %H:%M:%OS'),但我只得到了"2016-09-30 11:42:00 UTC",没有毫秒。然而,模式变为“数字”,这应该是朝着正确方向迈出的一步。我只设置了options(digits.secs=3)

我真的很感谢你的帮助。先感谢您。

1 个答案:

答案 0 :(得分:2)

x = c("30-09-2016 11:45:00,000", "01-10-2016 06:19:57,860", "01-10-2016 06:20:46,393")
format(as.POSIXct(gsub(",", ".", x), format='%d-%m-%Y %H:%M:%OS'), '%d-%m-%Y %H:%M:%OS3')
#[1] "30-09-2016 11:45:00.000" "01-10-2016 06:19:57.859" "01-10-2016 06:20:46.392"

OR

x = c("30-09-2016 11:45:00,000", "01-10-2016 06:19:57,860", "01-10-2016 06:20:46,393")

#Converting to POSIXct
options(digits.secs=3)
y = as.POSIXct(gsub(",", ".", x), format='%d-%m-%Y %H:%M:%OS', tz = "UTC")
y
#[1] "2016-09-30 11:45:00.000 UTC" "2016-10-01 06:19:57.859 UTC" "2016-10-01 06:20:46.392 UTC"

#Converting to numeric
as.numeric(y)
#[1] 1475253900 1475320798 1475320846

#Converting numeric back to POSIXct
as.POSIXct(as.numeric(y), origin = "1970-01-01", tz = "UTC")
#[1] "2016-09-30 11:45:00.000 UTC" "2016-10-01 06:19:57.859 UTC" "2016-10-01 06:20:46.392 UTC"

OR

x = c("30-09-2016 11:45:00,000", "01-10-2016 06:19:57,860", "01-10-2016 06:20:46,393")
library(lubridate)
options(digits.secs=3)
dmy_hms(gsub(",", ".", x))
#[1] "2016-09-30 11:45:00.000 UTC" "2016-10-01 06:19:57.860 UTC" "2016-10-01 06:20:46.393 UTC"