Python| os.path.getctime() 方法
Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。 os.path模块是Python中OS 模块的子模块,用于常见的路径名操作。
Python中的os.path.getctime()
方法用于获取系统指定路径的ctime 。这里ctime指的是UNIX中指定路径的最后一次元数据更改,而在Windows中,它指的是路径创建时间。
此方法返回一个浮点值,该值表示自纪元以来的秒数。如果文件不存在或无法访问,此方法会引发OSError 。
注意:纪元代表时间开始的点。它依赖于平台。对于 Unix,纪元是 1970 年 1 月 1 日 00:00:00 (UTC)。
Syntax: os.path.getctime(path)
Parameter:
path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.
Return Type: This method returns a floating-point value of class ‘float’ that represents the ctime (in seconds) for the specified path.
代码 #1:使用 os.path.getctime() 方法
# Python program to explain os.path.getctime() method
# importing os and time module
import os
import time
# Path
path = '/home/User/Documents/file.txt'
# Get the ctime of last
# for the specified path
c_time = os.path.getctime(path)
print("ctime since the epoch:", c_time)
# convert the ctime in
# seconds since epoch
# to local time
local_time = time.ctime(c_time)
print("ctime (Local time):", local_time)
ctime since the epoch: 1558447897.3122742
ctime (Local time): Tue May 21 19:41:37 2019
代码 #2:使用 os.path.getctime() 方法时处理错误
# Python program to explain os.path.getctime() method
# importing os, time and sys module
import os
import sys
import time
# Path
path = '/home/User/Documents/file2.txt'
# Get the ctime
# for the specified path
try:
c_time = os.path.getctime(path)
print("ctime since the epoch:", c_time)
except OSError:
print("Path '%s' does not exists or is inaccessible" %path)
sys.exit()
# convert ctime in
# seconds since epoch
# to local time
local_time = time.ctime(c_time)
print("ctime(Local time):", local_time)
# above code will print
# path does not exists or is inaccessible'
# if the specified path does not
# exists or is inaccessible
Path '/home/User/Documents/file2.txt' does not exists or is inaccessible
参考: https://docs。 Python.org/3/library/os.path.html