Python os.path.getctime() 方法用于获取文件或目录的创建时间。创建时间表示上次更改文件或目录的元数据的时间。除了创建时间之外,这包括对文件权限、所有权或其他元数据的更改。
该方法返回一个浮点数,表示指定路径的创建时间,以自纪元(1970 年 1 月 1 日,00:00:00 UTC)以来的秒数为单位。
如果指定的路径不存在,或者存在阻止访问该路径的权限问题,该方法将分别引发 FileNotFoundError 或 PermissionError。
语法
以下是 Python os.path.getctime() 方法的基本语法 -
参数
此方法接受一个字符串作为参数,该参数表示要检索其创建时间的文件的路径。
返回值
该方法返回一个浮点数,该数字表示自创建文件时的纪元(1970 年 1 月 1 日)以来的秒数。
例在以下示例中,我们将检索位于给定路径 “file_Path” 的文件的创建时间,并以自 epoch 以来的秒为单位打印它 -
输出
获得的输出如下 -
The file was created at: 1640227200.0
例
在这里,我们检索当前目录的创建时间,并以自 epoch 以来的秒为单位打印它 -
输出
以下是上述代码的输出 -
The directory was created at: 1656958586.0913115
例
此示例使用人类可读格式的 getctime() 方法检索位于 Windows 系统上的文件的创建时间 -
输出
我们得到的输出如下所示 -
Thu Sep 14 17:25:33 2024
例
如果我们尝试检索不存在的文件路径的创建时间,getctime() 方法会引发 “FileNotFoundError” -
输出
生成的结果如下所示 -
Traceback (most recent call last):
File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in <module>
ctime = os.path.getctime(link_path)
File "<frozen genericpath>", line 77, in getctime
FileNotFoundError: [WinError 3] The system cannot find the path specified: '/non/existent/path'
File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in <module>
ctime = os.path.getctime(link_path)
File "<frozen genericpath>", line 77, in getctime
FileNotFoundError: [WinError 3] The system cannot find the path specified: '/non/existent/path'