以跨平台方式获取某种修改日期很容易 – 只需调用
os.path.getmtime(path),您将获得上次修改路径上的文件时的Unix时间戳。
另一方面,获取文件创建日期是精巧和平台相关的,即使在三个大操作系统之间也不同:
>在Windows上,文件的ctime(记录在https://msdn.microsoft.com/en-us/library/14h5k7ff.aspx)存储其创建日期。你可以通过调用os.stat()的os.path.getctime()或.st_ctime的属性在Python中访问这个。这将不能在Unix上运行,其中ctime is the last time that the file’s attributes or content were changed。
>在Mac上,以及一些其他基于Unix的操作系统,您可以使用调用os.stat()的结果的.st_birthtime属性。
>在Linux上,这是目前不可能的,至少没有为Python编写C扩展。虽然一些文件系统常用于Linux do store creation dates(例如,ext4将它们存储在st_crtime中),Linux内核offers no way of accessing them;特别是从C(从最后的内核版本,don’t contain any creation date fields)的stat()调用返回的结构。你也可以看到标识符st_crtime目前不在Python source的任何地方。至少如果你在ext4 ,数据被附加到文件系统中的inode,但是没有方便的方式来访问它。
Linux上下一个最好的事情是通过os.stat()结果的os.path.getmtime()或.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