当前位置:首页 > 编程技术 > 正文

如何获取文件的最后保存时间

如何获取文件的最后保存时间

在Python中,可以使用`os`模块的`stat`函数来获取文件的最后保存时间(也称为最后修改时间)。以下是如何获取文件最后修改时间的步骤和代码示例:1. 导入`os...

在Python中,可以使用`os`模块的`stat`函数来获取文件的最后保存时间(也称为最后修改时间)。以下是如何获取文件最后修改时间的步骤和代码示例:

1. 导入`os`模块。

2. 使用`os.stat()`函数获取文件的元数据。

3. 从元数据中提取`st_mtime`属性,该属性表示文件最后修改的时间戳。

4. 将时间戳转换为人类可读的格式,例如使用`datetime`模块。

下面是具体的代码实现:

```python

import os

import datetime

def get_last_modified_time(file_path):

获取文件状态信息

file_stat = os.stat(file_path)

获取最后修改时间的时间戳

modification_time = file_stat.st_mtime

将时间戳转换为可读的日期时间格式

readable_time = datetime.datetime.fromtimestamp(modification_time)

return readable_time

示例使用

file_path = 'example.txt' 请替换为实际的文件路径

last_modified = get_last_modified_time(file_path)

print(f"The last modified time of the file is: {last_modified

最新文章