我怎么获取文件的创建和修改日期/时间?
你有几种选择。首先,你可以使用 os.path.getmtime
和 os.path.getctime
函数:
import os.path, time print("last modified: %s" % time.ctime(os.path.getmtime(file))) print("created: %s" % time.ctime(os.path.getctime(file)))
你的另一个选择是使用 os.stat
:
import os, time (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(file) print("last modified: %s" % time.ctime(mtime))
注意: ctime()
在 Unix 系统上不指创建时间,而是指 inode 数据最后一次更改的时间。(感谢 kojiro 在评论中提供了一个有趣的博客文章链接,使这个事实更加清晰)
以跨平台的方式获取某个文件的修改日期很容易 - 只需调用os.path.getmtime(path)
,就可以获取位于path
的文件的Unix时间戳,表示该文件最后一次修改的时间。
然而,获取文件创建日期却很麻烦,而且在三个大的操作系统之间还有所不同:
- 在Windows上,一个文件的
ctime
(详见https://msdn.microsoft.com/en-us/library/14h5k7ff.aspx)中存储了它的创建日期。在Python中,可以通过调用os.path.getctime()
或通过调用os.stat()
的返回结果的.st_ctime
属性来访问它。但是,在Unix上这种方式行不通,因为ctime
是指文件的属性或内容最后一次更改的时间。 - 在Mac以及其他一些基于Unix的操作系统上,可以通过调用
os.stat()
的结果的.st_birthtime
属性来获取创建日期。 -
在Linux上,目前似乎是不可能的,至少不能在Python中直接实现。尽管一些与Linux常用的文件系统(例如
ext4
)一起使用时会存储创建日期(将其存储在st_crtime
中),但是Linux内核却没有提供访问它们的方法。特别是,它从系统调用stat()
返回的结构体,最新的内核版本中不包含任何创建日期字段。您还可以看到,标识符st_crtime
目前在Python源中无处出现。如果您使用的是ext4
,则数据已附加到文件系统中的inodes,但是没有方便的方法来访问它。
在Linux操作系统中获取文件的下一个最佳方法是通过os.path.getmtime()
或os.stat()
结果的.st_mtime
属性来访问文件的mtime
。这将给你文件内容被修改的最后时间,对于某些用例,这可能足够了。
将所有这些内容合并起来,跨平台代码应该长这样...
import os import platform def creation_date(path_to_file): """ Try to get the date that a file was created, falling back to when it was last modified if that isn't possible. See http://stackoverflow.com/a/39501288/1709587 for explanation. """ if platform.system() == 'Windows': return os.path.getctime(path_to_file) else: stat = os.stat(path_to_file) try: return stat.st_birthtime except AttributeError: # We're probably on Linux. No easy way to get creation dates here, # so we'll settle for when its content was last modified. return stat.st_mtime