gpt4 book ai didi

r - 在 R 中,为什么我会在 POSIXct 和 POSIXlt 之间获得一毫秒的差异?

转载 作者:行者123 更新时间:2023-12-04 15:51:59 24 4
gpt4 key购买 nike

这个片段

options(digits.secs=3)
s<-"12:00:00.188"
fmt<-"%I:%M:%OS"
print(strptime(s,fmt))
print(as.POSIXct(strptime(s,fmt)))

给出这个文本输出:
[1] "2017-09-12 00:00:00.188 CEST"
[1] "2017-09-12 00:00:00.187 CEST"

虽然我希望上述结果是相同的。我错过了什么?

我的 session 信息:
print(sessionInfo())

给出:
R version 3.4.0 (2017-04-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

Matrix products: default

locale:
[1] LC_COLLATE=Italian_Italy.1252 LC_CTYPE=Italian_Italy.1252 LC_MONETARY=Italian_Italy.1252 LC_NUMERIC=C
[5] LC_TIME=Italian_Italy.1252

attached base packages:
[1] stats graphics grDevices utils datasets methods base

loaded via a namespace (and not attached):
[1] compiler_3.4.0 tools_3.4.0

在 Linux 中的结果相同:
R version 3.3.3 (2017-03-06)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Debian GNU/Linux 9 (stretch)

locale:
[1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
[7] LC_PAPER=en_US.UTF-8 LC_NAME=C LC_ADDRESS=C LC_TELEPHONE=C LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats graphics grDevices utils datasets methods base

loaded via a namespace (and not attached):
[1] tools_3.3.3

编辑(在 Roland's comment 之后)

也许我错了,但在我看来 0.002 不能用浮点表示,仍然有 0.002 POSIXct 和 POSIXlt 之间没有区别:
options(digits.secs=3)
s<-"12:00:00.002"
fmt<-"%I:%M:%OS"
print(strptime(s,fmt))
print(as.POSIXct(strptime(s,fmt)))

给出:
[1] "2017-09-12 00:00:00.002 CEST"
[1] "2017-09-12 00:00:00.002 CEST"

最佳答案

您可以在 datetime 的文档中阅读有关此内容的信息:https://stat.ethz.ch/R-manual/R-devel/library/base/html/DateTimeClasses.html

特别是:

Class "POSIXct" represents the (signed) number of seconds since the beginning of 1970 (in the UTC time zone) as a numeric vector.


strptime和其他类(class) POSIXlt以不同的方式存储日期时间。

所以亚秒级精度存在问题:

Sub-second Accuracy

Classes "POSIXct" and "POSIXlt" are able to express fractions of a second. (Conversion of fractions between the two forms may not be exact, but will have better than microsecond accuracy.)



所以,你会看到 POSIXltstrptime准确打印这些:
strptime(s,fmt)
as.POSIXlt(strptime(s,fmt), format = "%Y-%m-%d %H:%M:%OS")

但是,因为 POSIXct进行计算以将日期表示为数字,由于浮点精度、闰秒等原因,它可能会不准确。

关于r - 在 R 中,为什么我会在 POSIXct 和 POSIXlt 之间获得一毫秒的差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46179314/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com