lan*_*dau 17 timestamp r filemtime
在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中的精确文件时间戳?
我认为新的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"
Run Code Online (Sandbox Code Playgroud)
这可以形式化为一个为您做更多事情的函数:
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"
Run Code Online (Sandbox Code Playgroud)
既然您要求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"
Run Code Online (Sandbox Code Playgroud)
请注意,缺少小数秒是打印的产物(如您所述),这可以补救:
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"
Run Code Online (Sandbox Code Playgroud)
更新:在 Mac 上测试后,我确认了几件事(感谢 @HongOoi 的产品):(1)stat确实不同,不支持相同的命令行选项,因此需要更新此脚本;(2)这个答案表明文件系统甚至没有存储文件时间的亚秒分辨率。如果您的文件系统类型是 HFS+,我认为这里可能无需执行任何操作。如果底层文件系统不同,您可能会得到更好的结果。
确实,Windows 不附带stat可执行文件。然而,Windows 版的 Git(有些人认为这是分析师/开发工具包中的必需品)可以在/Program Files/Git/usr/bin/stat.exe. (事实上,我上面的 hack 是在 Windows 上编写的,然后在 Ubuntu 上进行了测试。)
不幸的是,最重要的是,根据您的文件系统类型,您可能无法在 MacOS 上获得您想要/需要的内容。我无法让安装程序stat提供亚秒分辨率(即使有不同的参数),这表明我引用的 4 年前的答案没有改变。
| 归档时间: |
|
| 查看次数: |
675 次 |
| 最近记录: |