def get_modified_time(path):
ts = os.path.getmtime(path)
return datetime.fromtimestamp(ts).replace(microsecond=0)
这段代码定义了一个函数 `get_modified_time`,它接受一个路径 `path` 作为参数,并返回该路径所指向的文件或目录的最后修改时间。
1. `os.path.getmtime(path)`: 使用 `os` 模块的 `path.getmtime` 方法获取指定路径 `path` 的最后修改时间(以秒为单位的时间戳)。
2. `datetime.fromtimestamp(ts)`: 使用 `datetime` 模块的 `fromtimestamp` 方法将时间戳 `ts` 转换为 `datetime` 对象。
3. `.replace(microsecond=0)`: 将 `datetime` 对象中的微秒部分设置为0。
举例说明:
假设我们有一个名为 `example.txt` 的文件,其内容如下:
```
Hello, world!
```
我们可以使用以下代码来获取该文件的最后修改时间:
import os
import datetime
def get_modified_time(path):
ts = os.path.getmtime(path)
return datetime.fromtimestamp(ts).replace(microsecond=0)
file_path = "example.txt"
modified_time = get_modified_time(file_path)
print(modified_time)
输出:
2023-08-22 15:23:45
在这个例子中,我们首先导入了 `os` 和 `datetime` 模块,然后定义了 `get_modified_time` 函数。接下来,我们指定了文件路径 `example.txt`,并使用 `get_modified_time` 函数获取该文件的最后修改时间。最后,我们打印出获取的时间。在这个例子中,假设我们在2023年8月22日15:23:45修改了 `example.txt` 文件,因此输出的时间戳是 `2023-08-22 15:23:45`。