當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python os.path.getctime()用法及代碼示例

Python中的OS模塊提供了與操作係統進行交互的函數。操作係統屬於Python的標準實用程序模塊。該模塊提供了使用依賴於操作係統的函數的便攜式方法。 os.path模塊是Python中OS模塊的子模塊,用於通用路徑名操作。

os.path.getctime()Python中的方法用於獲取係統指定路徑的ctime。這裏的ctime是指UNIX中指定路徑的最後一次元數據更改,而在Windows中是指路徑創建時間。此方法返回一個浮點值,該值表示自紀元以來的秒數。如果文件不存在或無法訪問,則此方法引發OSError。

注意:紀元代表時間開始的時間點。它取決於平台。對於Unix,紀元是1970年1月1日,00:00:00(UTC)。


用法: os.path.getctime(path)

參數:
path:代表文件係統路徑的path-like對象。 path-like對象是表示路徑的字符串或字節對象。

返回類型:此方法返回“ 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

參考: https://docs.python.org/3/library/os.path.html



相關用法


注:本文由純淨天空篩選整理自ihritik大神的英文原創作品 Python | os.path.getctime() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。