将毫秒添加到 R 中的时间戳,即使原始字符没有毫秒?

Adding milliseconds to a timestamp in R, even though the original character does not have milliseconds?

我正在做一些动物运动分析,我想将数据提交给一个名为 Movebank 的组织进行注释,但他们要求时间戳包含毫秒,小数点后 3 位。

我的数据框 (dat) 中有一列,我的时间戳是字符(没有毫秒),例如 "2017-07-19 16:30:24"

要将它们转换为以毫秒为单位的时间和日期格式,我正在使用代码:

options(digits.secs = 3)
dat$timestamp <- as.POSIXct(dat$timestamp, format = "%Y-%m-%d %H:%M:%OS", tz = "UTC")

这在将我的时间戳列转换为 POSIXct 时效果很好,我可以用它来制作曲目等,但它不会像我希望的那样在每个时间戳的末尾添加 .000 毫秒。

我也试过:

dat$timestamp <- as.POSIXct(dat$timestamp, format = "%Y-%m-%d %H:%M:%OS3", tz = "UTC")

(注:我加了.. %OS3 ...) 但是这个 returns 一个 NA 我的时间戳。

任何人都可以阐明这一点吗?我基本上需要在我的每个时间戳的末尾添加 .000,以便使用上面给出的示例,我将具有格式 "2017-07-19 16:30:24.000"

如果没有有效毫秒数的时间,则毫秒数将被舍弃。

options(digits.secs=4)

x1 <- as.POSIXct("2017-07-19 16:30:25")
as.POSIXct(paste0(x1, ".000"), format="%Y-%m-%d %H:%M:%OS")
# [1] "2017-07-19 16:30:25 UTC"

但是,如果有,它们将被自动添加。

x2 <- as.POSIXct("2017-07-19 16:30:25.002")
c(x1, x2)
# [1] "2017-07-19 18:30:25.000 CEST" "2017-07-19 18:30:25.002 CEST"