17

在 Windows 7 和 Mac OS 10.12.2(使用 R 3.3.2)上,似乎file.mtime()严重舍入或截断时间戳。我验证file.create("my_file.txt"); print(as.numeric(file.mtime("my_file.txt")), digits = 22)了在 Linux 上打印出小数点后的几位数字,但小数点后的所有内容在 Windows 7 上都消失了my_file.txt。Mac OS 10.12.2 的行为类似于 Windows 7。在 R 中是否有独立于平台的方法来获取精确的文件时间戳?

4

2 回答 2

6

您可以等待大约 2 周,此时 R 3.3.3 将解决此问题(至少对于 Windows)。从新闻文件:

(仅限 Windows。)file.info() 现在返回文件时间戳,包括几分之一秒;自 R 2.14.0 以来,它已经在其他平台上这样做了。(注意:一些文件系统不记录修改和访问时间戳到亚秒级分辨率。)

于 2017-02-11T18:39:45.390 回答
3

我认为新file.info的可能是最好的方法。如果 R-3.3.3 没有带来您需要的东西(或者在此期间,如果有的话),您可以尝试通过利用stat可能安装在基本操作系统中的事实来回避它(我没有在一个苹果电脑):

as.POSIXct(system2("stat", args = c("-c", "%y", "my_file.txt"), stdout = TRUE))
# [1] "2017-02-15 11:24:13 PST"

这可以在一个为你做更多事情的函数中形式化:

my_mtime <- function(filenames, stat = c("modified", "birth", "access", "status"),
                     exe = Sys.which("stat")) {
  if (! nzchar(exe)) stop("'stat' not found")
  stat <- switch(match.arg(stat), birth = "%w", access = "%x", modified = "%y", status = "%z")
  filenames <- Sys.glob(filenames) # expand wildcards, remove missing files
  if (length(filenames)) {
    outs <- setNames(system2(exe, args = c("-c", stat, shQuote(filenames)), stdout = TRUE),
                     nm = filenames)
    as.POSIXct(outs)
  }
}

my_mtime("[bh]*")
#                  b-file.R                  h-file.R 
# "2017-02-14 05:46:34 PST" "2017-02-14 05:46:34 PST"

既然您要求file.mtime,我假设“修改”对您来说是最有趣的,但包含其他一些文件时间戳很容易:

my_mtime("[bh]*", stat="birth")
#                  b-file.R                  h-file.R 
# "2017-02-13 22:04:01 PST" "2017-02-13 22:04:01 PST" 
my_mtime("[bh]*", stat="status")
#                  b-file.R                  h-file.R 
# "2017-02-14 05:46:34 PST" "2017-02-14 05:46:34 PST" 

请注意,缺少小数秒是打印的产物(如您所述),可以对此进行补救:

x <- my_mtime("[bh]*", stat="status")
x
#                  b-file.R                  h-file.R 
# "2017-02-14 05:46:34 PST" "2017-02-14 05:46:34 PST" 
options(digits.secs = 6)
x
#                         b-file.R                         h-file.R 
# "2017-02-14 05:46:34.307046 PST" "2017-02-14 05:46:34.313038 PST" 
class(x)
# [1] "POSIXct" "POSIXt" 

更新:在 Mac 上进行测试后,我确认了几件事(感谢 @HongOoi 提供的产品):(1)stat确实不同,不支持相同的命令行选项,因此需要更新此脚本;(2)这个答案表明文件系统甚至没有在文件时间上存储亚秒级分辨率。如果您的文件系统类型是 HFS+,我认为这里可能无事可做。如果底层文件系统不同,您可能会得到更好的结果。

确实,Windows 没有附带stat可执行文件。但是,Windows 版 Git(有人认为这是分析师/开发工具包中的必需品)在/Program Files/Git/usr/bin/stat.exe. (事实上​​,我上面的 hack 是在 Windows 上编写的,在 Ubuntu 上进行了第二次测试。)

不幸的是,最重要的是,根据您的文件系统类型,您可能无法在 MacOS 上获得您想要/需要的东西。我无法让安装程序stat给出亚秒级的分辨率(即使有不同的论点),这表明我引用的 4 年前的答案没有改变。

于 2017-02-15T21:49:11.123 回答