本文目录导读:

- 方法1:使用
os.path.getmtime()(推荐) - 方法2:使用
os.stat() - 方法3:使用
pathlib(Python 3.4+) - 完整示例:比较三种时间
- 格式化时间输出
- 错误处理示例
- 批量处理多个文件
在Python中获取文件修改时间有多种方法,以下是几种常见的方式:
方法1:使用 os.path.getmtime() (推荐)
import os
import time
from datetime import datetime
# 文件路径
file_path = "example.txt"
# 获取修改时间(时间戳)
modification_time = os.path.getmtime(file_path)
print(f"修改时间戳: {modification_time}")
# 转换为可读格式
readable_time = time.ctime(modification_time)
print(f"可读时间: {readable_time}")
# 转换为datetime对象
dt = datetime.fromtimestamp(modification_time)
print(f"datetime格式: {dt}")
print(f"格式化时间: {dt.strftime('%Y-%m-%d %H:%M:%S')}")
方法2:使用 os.stat()
import os
import time
from datetime import datetime
file_path = "example.txt"
# 获取文件状态信息
file_stats = os.stat(file_path)
# 获取修改时间(st_mtime)
modification_time = file_stats.st_mtime
print(f"修改时间戳: {modification_time}")
# 转换为可读格式
readable_time = time.ctime(modification_time)
print(f"可读时间: {readable_time}")
# 转换为datetime对象
dt = datetime.fromtimestamp(modification_time)
print(f"格式化时间: {dt.strftime('%Y-%m-%d %H:%M:%S')}")
方法3:使用 pathlib(Python 3.4+)
from pathlib import Path
import time
from datetime import datetime
file_path = Path("example.txt")
# 获取修改时间
modification_time = file_path.stat().st_mtime
print(f"修改时间戳: {modification_time}")
# 转换为可读格式
readable_time = time.ctime(modification_time)
print(f"可读时间: {readable_time}")
# 转换为datetime对象
dt = datetime.fromtimestamp(modification_time)
print(f"格式化时间: {dt.strftime('%Y-%m-%d %H:%M:%S')}")
完整示例:比较三种时间
import os
import time
from datetime import datetime
def get_file_times(file_path):
"""获取文件的三种时间"""
try:
# 获取文件状态
stats = os.stat(file_path)
# 三种时间
access_time = stats.st_atime # 访问时间
modify_time = stats.st_mtime # 修改时间
create_time = stats.st_ctime # 创建时间(Windows)/ 状态改变时间(Unix)
print(f"文件: {file_path}")
print(f"访问时间: {time.ctime(access_time)}")
print(f"修改时间: {time.ctime(modify_time)}")
print(f"创建时间: {time.ctime(create_time)}")
return {
'access': access_time,
'modify': modify_time,
'create': create_time
}
except FileNotFoundError:
print(f"文件 {file_path} 不存在")
return None
# 使用示例
get_file_times("test.txt")
格式化时间输出
import os
from datetime import datetime
file_path = "example.txt"
# 获取修改时间
mtime = os.path.getmtime(file_path)
# 多种格式化方式
dt = datetime.fromtimestamp(mtime)
formats = [
'%Y-%m-%d %H:%M:%S', # 2024-01-15 14:30:25
'%Y年%m月%d日 %H:%M:%S', # 2024年01月15日 14:30:25
'%Y-%m-%d', # 2024-01-15
'%H:%M:%S', # 14:30:25
'%Y/%m/%d %H:%M', # 2024/01/15 14:30
'%a %b %d %H:%M:%S %Y', # Mon Jan 15 14:30:25 2024
]
for fmt in formats:
print(f"{fmt}: {dt.strftime(fmt)}")
错误处理示例
import os
from datetime import datetime
def safe_get_modification_time(file_path):
"""安全获取文件修改时间"""
try:
if not os.path.exists(file_path):
return f"错误: 文件 '{file_path}' 不存在"
if not os.path.isfile(file_path):
return f"错误: '{file_path}' 不是一个文件"
mtime = os.path.getmtime(file_path)
dt = datetime.fromtimestamp(mtime)
return dt.strftime('%Y-%m-%d %H:%M:%S')
except PermissionError:
return f"错误: 没有权限访问 '{file_path}'"
except OSError as e:
return f"错误: {e}"
# 使用示例
result = safe_get_modification_time("example.txt")
print(result)
批量处理多个文件
import os
from datetime import datetime
import glob
def get_all_files_modification_time(directory, pattern="*"):
"""获取目录下所有匹配文件的修改时间"""
files_info = []
# 获取所有匹配的文件
for file_path in glob.glob(os.path.join(directory, pattern)):
if os.path.isfile(file_path):
mtime = os.path.getmtime(file_path)
dt = datetime.fromtimestamp(mtime)
files_info.append({
'filename': os.path.basename(file_path),
'modify_time': dt.strftime('%Y-%m-%d %H:%M:%S'),
'modify_timestamp': mtime
})
# 按修改时间排序
files_info.sort(key=lambda x: x['modify_timestamp'], reverse=True)
return files_info
# 使用示例
files = get_all_files_modification_time(".", "*.txt")
for file_info in files:
print(f"{file_info['filename']}: {file_info['modify_time']}")
推荐使用 os.path.getmtime() 方法,因为它最简洁直接,Python 的官方文档也推荐这种方式获取文件修改时间。