比较R中的纳秒精度时间戳



虽然这是一个非常常见的实用程序,但许多人可能需要,但奇怪的是Google并未向我展示任何匹配的答案。我有一个时间戳记,该格式以 HH:MM:SS.NANOSECONDPRECISION 9二元在几秒钟后。我在R中有2列,我需要找到差异。我找不到如何使用posix,我们可以将这种字符时间戳转换为可比的数字。

发送时间-11:20:30.791372292接收时间11:20:30.791382216找到这两个时间戳之间差异的好方法

我即将发布一个包裹到cran,您目前可以从 @roland建议的方式从github那里获得,该软件包以 @roland建议的方式来处理这一点 - 作为s3扩展名和rcppcctz。

举例说明:

R> sentt <- nanotime("2016-12-21T11:20:30.791372292+00:00")
R> receivet <- nanotime("2016-12-21T11:20:30.791382216+00:00")
R> format(c(sentt, receivet))
[1] "1482319230791372292" "1482319230791382216"
R> format(sentt)
[1] "2016-12-21T11:20:30.791372292+00:00"
R> format(receivet)
[1] "2016-12-21T11:20:30.791382216+00:00"
R> receivet-sentt
integer64
[1] 9924
R> 

i(当前)使用固定格式进行解析,这很容易概括。我还需要添加一个日期(因为您永远不能只用时间来解析日期,它是不确定的),并且出于分析字符串原因添加了0。

的TZ Offet。

我们发现了两个时间戳之间的9924 NSEC AKA 9.924 microsec。在我的行业中,听起来像是tick trick trade的指标:)

只要可以肯定地假设您的时间始终在同一日期,以下日期将起作用。它每次都会重新计算,因为自一天开始以来发生的纳秒数量。它假设使用24小时时间。

sent_time <- "11:20:30.791372292"
receive_time <- "11:20:30.791382216"
convert_nano <- function(x){
  require(magrittr)
  split <- 
    #* split up the time components
    strsplit(x, ":") %>%
    #* convert strings to numerics
    lapply(as.numeric) %>%
    #* convert each component to nanoseconds
    vapply(function(s) sum(s * c(3600, 60, 1) * 10 ^ 9),
           numeric(1))
}
convert_nano(receive_time) - convert_nano(sent_time)

如果您会在不同的日子遇到时间,则可能采用类似的方法,但可能要考虑可能在两次之间的天数上限。如果您有两天的时间,您将无法充分代表纳秒。

我会分别处理子秒:

times <- c("11:20:30.791372292", "11:20:30.791382216")
library(chron)
fulltimes <- round(as.numeric(times(times)) * 24 * 3600)
subtimes <- as.numeric(gsub(".+(?=\.)", "0", times, perl = TRUE))
#difference
sprintf("%.9f", fulltimes[2] - fulltimes[1] + subtimes[2] - subtimes[1])
#[1] "0.000009924"

您可以轻松地创建一个S3类,并使用此次命处理和适当的S3方法扩展Chron。

最新更新