在Linux上用Python获取文件创建时间

24 投票
7 回答
15117 浏览
提问于 2025-04-15 14:14

os.stat这个函数会返回文件的一些信息,其中包括两个时间属性:st_mtime和st_ctime。st_mtime是文件最后修改的时间,而st_ctime则是文件状态改变的时间。在POSIX系统中,这两个时间的含义是这样的。那有没有什么方法可以用Python在Linux系统下获取文件的创建时间呢?

7 个回答

4

由于没有合适的工具,我自己创建了一个叫做 crtime 的工具。

pip install crtime

然后你可以这样使用它:

sudo crtime ./

这将输出:

1552938281  /home/pascal/crtime/.gitignore
1552938281  /home/pascal/crtime/README.md
1552938281  /home/pascal/crtime/crtime
1552938281  /home/pascal/crtime/deploy.py
1552938281  /home/pascal/crtime/setup.cfg
1552938281  /home/pascal/crtime/setup.py
1552938961  /home/pascal/crtime/crtime.egg-info
1552939447  /home/pascal/crtime/.git
1552939540  /home/pascal/crtime/build
1552939540  /home/pascal/crtime/dist

请注意,对于大文件夹来说,它的速度会比上面的 xstat 快1000倍,因为它会先创建一个临时文件,然后一次性对所有文件执行 stat 调用。

在Python中使用时(别忘了在Linux上需要用sudo来运行):

from crtime import get_crtimes, get_crtimes_in_dir
get_crtimes_in_dir("./")
15

尝试一下:

st_birthtime

不过,这些功能并不是在所有系统上都能用。根据文档:

在一些Unix系统(比如Linux)上,可能会有以下属性可用:st_blocks(为文件分配的块数)、st_blksize(文件系统的块大小)、st_rdev(如果是设备文件,则表示设备类型)、st_flags(用户定义的文件标志)。

在其他Unix系统(比如FreeBSD)上,可能会有以下属性可用(但可能只有在root用户尝试使用时才会填充这些信息):st_gen(文件生成编号)、st_birthtime(文件创建时间)。

http://docs.python.org/2/library/os.html#os.stat

26

你可能无法做到确实不行。

3.1)  How do I find the creation time of a file?

      You can't - it isn't stored anywhere.  Files have a last-modified
      time (shown by "ls -l"), a last-accessed time (shown by "ls -lu")
      and an inode change time (shown by "ls -lc"). The latter is often
      referred to as the "creation time" - even in some man pages -
      but that's wrong; it's also set by such operations as mv, ln,
      chmod, chown and chgrp.

      The man page for "stat(2)" discusses this.

撰写回答