gpt4 book ai didi

r - 使用亚毫秒日期时间从字符->POSIXct->字符准确转换

转载 作者:行者123 更新时间:2023-12-04 13:33:09 25 4
gpt4 key购买 nike

我在文件中有一个字符日期时间列。我加载文件(到 data.table 中)并执行需要将列转换为 POSIXct 的操作.然后我需要写 POSIXct值返回文件,但日期时间将不相同(因为它打印不正确)。

这个打印/格式问题是众所周知的,并且已经讨论过多次。我读过一些描述这个问题的帖子。我找到的最权威的回答是回复this question .该问题的答案提供了两个函数( myformat.POSIXctform )来解决这个问题,但它们似乎不适用于这个例子:

x <- "04-Jan-2013 17:22:08.139"
options("digits.secs"=6)
form(as.POSIXct(x,format="%d-%b-%Y %H:%M:%OS"),format="%d-%b-%Y %H:%M:%OS3")
[1] "04-Jan-2013 17:22:08.138"
form(as.POSIXct(x,format="%d-%b-%Y %H:%M:%OS"),format="%d-%b-%Y %H:%M:%OS4")
[1] "04-Jan-2013 17:22:08.1390"
myformat.POSIXct(as.POSIXct(x,format="%d-%b-%Y %H:%M:%OS"),digits=3)
[1] "2013-01-04 17:22:08.138"
myformat.POSIXct(as.POSIXct(x,format="%d-%b-%Y %H:%M:%OS"),digits=4)
[1] "2013-01-04 17:22:08.1390"

我的 sessionInfo :
R version 2.15.2 (2012-10-26)
Platform: x86_64-w64-mingw32/x64 (64-bit)

locale:
[1] LC_COLLATE=English_United Kingdom.1252 LC_CTYPE=English_United Kingdom.1252
[3] LC_MONETARY=English_United Kingdom.1252 LC_NUMERIC=C
[5] LC_TIME=C

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

other attached packages:
[1] fasttime_1.0-0 data.table_1.8.9 bit64_0.9-2 bit_1.1-9
[5] sas7bdat_0.3 chron_2.3-43 vimcom_0.9-6

loaded via a namespace (and not attached):
[1] tools_2.15.2

最佳答案

所以我想你确实需要在我的建议中添加一些软糖因素:https://stackoverflow.com/a/7730759/210673 .这似乎有效,但可能包括其他错误;在用于任何重要的事情之前,请仔细测试并考虑它在做什么。

myformat.POSIXct <- function(x, digits=0) {
x2 <- round(unclass(x), digits)
attributes(x2) <- attributes(x)
x <- as.POSIXlt(x2)
x$sec <- round(x$sec, digits) + 10^(-digits-1)
format.POSIXlt(x, paste("%Y-%m-%d %H:%M:%OS",digits,sep=""))
}

关于r - 使用亚毫秒日期时间从字符->POSIXct->字符准确转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15383057/

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