python - 获取纳秒级精度的文件修改时间

标签 python linux datetime precision high-resolution-time

我需要为遍历文件系统树的 Python 2 程序中的每个文件获取完整的纳秒精度修改时间戳。我想在 Python 本身中执行此操作,因为为每个文件生成一个新的子进程会很慢。

来自 Linux 上的 C 库,you can get nanosecond-precision timestamps通过查看 st_mtime_nsec领域stat结果。例如:

#include <sys/stat.h>
#include <stdio.h>
int main() {
    struct stat stat_result;
    if(!lstat("/", &stat_result)) {
        printf("mtime = %lu.%lu\n", stat_result.st_mtim.tv_sec, stat_result.st_mtim.tv_nsec);
    } else {
        printf("error\n");
        return 1;
    }
}

打印 mtime = 1380667414.213703287 (/ 在 ext4 文件系统上,支持纳秒时间戳,时钟为 UTC)。

同样,date --rfc-3339=ns --reference=/版画 2013-10-01 22:43:34.213703287+00:00 .

Python (2.7.3) 的 os.path.getmtime(filename)os.lstat(filename).st_mtime将时间设为 float .然而,结果是错误的:

In [1]: import os
In [2]: os.path.getmtime('/') % 1
Out[2]: 0.21370339393615723
In [3]: os.lstat('/').st_mtime % 1
Out[3]: 0.21370339393615723

——只有前 6 位数字是正确的,可能是由于 float 错误。

最佳答案

os.stat('/').st_mtime是一个float对象,对于纳秒级的时间戳,float的精度太低了,

Python’s underlying type for floats is an IEEE 754 double, which is only good for about 16 decimal digits. With ten digits before the decimal point, that leaves six for sub-second resolutions, which is three short of the range required to preserve POSIX nanosecond-resolution timestamps. via: This Week in Python Stupidity: os.stat, os.utime and Sub-Second Timestamps

如果您可以使用 Python 3,则有一个名为 st_mtime_ns 的新属性,它是以纳秒为单位的 st_mtime。试试吧。

>>> os.stat('.').st_mtime
1381571932.044594
>>> os.stat('.').st_mtime_ns
1381571932044593972

引用资料:

PEP 410 -- Use decimal.Decimal type for timestamps

os.stat(): add new fields to get timestamps as Decimal objects with nanosecond resolution

add st_*time_ns fields to os.stat(), add ns keyword to os.utime(), os.utimens() expects a number of nanoseconds

关于python - 获取纳秒级精度的文件修改时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19351867/

相关文章:

Python 和 Socket.IO - 应用程序在连接后挂起

linux - 如何传递命令行参数

date - 可以检测 ISO8601 字符串中的日期和时间格式吗?

.net - 从.net Data.ToBinary()中提取数据

python - 为什么在提供 int 系列时 pd.to_timedelta 会失败?

python - 在 Thonny IDE 中注释代码的键盘快捷键

python - Python-then-profile-then-C 设计模式的最佳实践?

python - 充当无限序列的对象的 __len__ 的正确返回值

linux - 从 shell 脚本内部记录 sql 错误

c++ - CURL download_progress 抛出 SIGSEGV