如何使用Python获取文件的创建和修改日期/时间?

要获取文件的创建时间,可以在Windows上使用os.path.getctime(file_path)。在UNIX系统上,您不能使用与上次更改文件属性或内容时返回的函数相同的函数。要在基于UNIX的系统上获得创建时间,请使用stat元组的st_birthtime属性。

 例

在Windows上-

>>> import os
>>> print os.path.getctime('my_file')
1505928271.0689342

它以自该纪元以来的秒数为单位给出时间。对于UNIX系统,

import os
stat = os.stat(path_to_file)
try:
    print(stat.st_birthtime)
except AttributeError:
    # Probably on Linux. No easy way to get creation dates here,
    # so we'll settle for when its content was last modified.
    print(stat.st_mtime)

输出结果

这将给出输出-

1505928271.0689342

要获取文件的修改时间,可以使用os.path.getmtime(path)。支持跨平台。例如

>>> import os
>>> print os.path.getmtime('my_file')
1505928275.3081832