答案:在Python中可通过os.path和pathlib模块获取文件时间;1. 使用os.path.getmtime()获取修改时间;2. os.path.getctime()在Windows返回创建时间,Linux为inode更改时间;3. pathlib提供更现代语法,file_path.stat().st_mtime和st_ctime对应修改和创建时间;4.Linux不支持真实创建时间,建议优先使用修改时间,时间戳可转为datetime对象处理。
在 Python 中读取文件的创建时间和修改时间,可以通过 os.path 模块和 pathlib 模块实现。不同操作系统对“创建时间”的支持有所不同:Windows 支持创建时间,macOS 部分支持,而 Linux 通常不提供创建时间,只能获取修改时间。
通过 os.path.getmtime() 可以获取文件的最后修改时间,返回的是时间戳(从 1970 年 1 月 1 日起的秒数):
import os import timefile_path = 'example.txt' modify_time = os.path.getmtime(file_path) print("修改时间:", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(modify_time)))
os.path.getctime() 在 Windows 上返回创建时间,在 Unix/Linux 上返回的是 inode 修改时间(不是创建时间):
create_time = os.path.getctime(file_path)
print("创建时间:", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(create_time)))
Python 3.4+ 推荐使用 pathlib,语法更清晰:
from pathlib import Path import timefile_path = Path('example.txt')
修改时间
modify_time = file_path.stat().st_mtime print("修改时间:", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(modify_time)))
创建时间(Windows 是创建时间)
create_time = file_path.stat().st_ctime print("创建时间:", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(create_time)))
from datetime import datetimedt_modify = datetime.fromtimestamp(modify_time) print("datetime 格式:", dt_modify)
基本上就这些。根据系统环境选择合适方法,注意平台差异即可。