Python os.path.getctime()
Python中的os.path.getctime()方法用于获取系统指定路径的ctime。这里的ctime指的是UNIX中指定路径的最后一次元数据更改,而在Windows中,它指的是路径创建时间。
此方法返回一个浮点值,表示自epoch以来的秒数。如果文件不存在或无法访问,此方法将引发OSError异常。
注意:epoch表示时间开始的点。它是平台相关的。对于Unix, epoch是1970年1月1日00:00:00 (UTC)。
语法:os.path.getctime(path)
参数:
path:表示文件系统路径的类路径对象。类路径对象是表示路径的字符串或字节对象。
返回类型:此方法返回类“float”的浮点值,该类表示指定路径的ctime(以秒为单位)。
示例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