
在python中处理文件时,获取其创建或修改时间是常见的需求,例如用于文件校验、归档或自动化流程。许多初学者可能会尝试使用类似os.path.gettime()这样的方法,但这通常会导致attributeerror: module 'ntpath' has no attribute 'gettime'错误,因为os.path模块并没有直接提供获取时间戳的功能。正确的做法是利用os模块提供的stat()函数来获取文件的详细元数据。
os.stat()函数返回一个包含文件状态信息的对象(os.stat_result)。这个对象包含了多个属性,其中与时间戳相关的主要是:
这些属性返回的是Unix时间戳(自1970年1月1日UTC午夜以来经过的秒数)。为了使其更具可读性,我们通常需要使用datetime模块将其转换为datetime对象。
以下代码演示了如何获取指定文件的修改时间和创建时间,并将其转换为易读的日期时间格式:
import os
import datetime
def get_file_timestamps(file_path):
"""
获取指定文件的修改时间和创建时间。
Args:
file_path (str): 文件的完整路径。
Returns:
tuple: 包含 (creation_datetime, modification_datetime) 的元组,
如果文件不存在则返回 (None, None)。
"""
if not os.path.exists(file_path):
print(f"错误:文件 '{file_path}' 不存在。")
return None, None
try:
# 获取文件的stat信息
file_stat = os.stat(file_path)
# 提取时间戳
creation_timestamp = file_stat.st_ctime
modification_timestamp = file_stat.st_mtime
# 将时间戳转换为datetime对象
creation_datetime = datetime.datetime.fromtimestamp(creation_timestamp)
modification_datetime = datetime.datetime.fromtimestamp(modification_timestamp)
return creation_datetime, modification_datetime
except OSError as e:
print(f"获取文件 '{file_path}' 时间戳时发生错误: {e}")
return None, None
# 示例用法
if __name__ == "__main__":
# 创建一个测试文件(如果不存在)
test_file_name = "example.txt"
if not os.path.exists(test_file_name):
with open(test_file_name, "w") as f:
f.write("这是一个测试文件。\n")
f.write("用于演示如何获取文件时间戳。")
print(f"已创建测试文件: {test_file_name}")
else:
print(f"测试文件已存在: {test_file_name}")
# 获取并打印文件时间戳
creation_dt, modification_dt = get_file_timestamps(test_file_name)
if creation_dt and modification_dt:
print(f"\n文件: {test_file_name}")
print(f"创建时间 (或元数据变更时间): {creation_dt}")
print(f"最后修改时间: {modification_dt}")
# 尝试获取一个不存在的文件的时间戳
print("\n尝试获取不存在的文件的时间戳:")
get_file_timestamps("non_existent_file.txt")通过os.stat()函数,Python提供了一种强大且灵活的方式来获取文件的元数据,包括其修改和创建(或元数据变更)时间戳。结合datetime模块,我们可以轻松地将这些原始时间戳转换为人类可读的日期时间格式。理解st_ctime的平台差异性,并实施适当的错误处理,是编写健壮文件操作代码的关键。掌握这一技巧,将有助于您更有效地管理和自动化文件相关的任务。
立即学习“Python免费学习笔记(深入)”;
以上就是Python文件时间戳获取:os.stat()的权威指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号