为什么 OS 中的模块 Python 只提供 Epoche Time 标准的输出?

Why OS Module in Python giving output of Epoche Time standard only?

为什么 Epoche Time 标准一次又一次地出现在我的输出中。我希望我的 Epoche Time 标准输出在 stat.ST_ATIME 中,但它在我的两个输出中都很受欢迎。

输入:

import os
import datetime
import stat

os.stat("abc.txt")

print("File size in byte is:",stat.ST_SIZE)
print("File last modified is:",datetime.datetime.fromtimestamp(stat.ST_MTIME))
print("File last accessed is:",datetime.datetime.fromtimestamp(stat.ST_ATIME))

输出:

File size in byte is: 6    
File last modified is: 1970-01-01 05:00:08
File last accessed is: 1970-01-01 05:00:07

预计:

File size in byte is: 6
File last modified is: 2021-08-21 05:00:08
File last accessed is: 1970-01-01 05:00:07

stat.ST_MTIME不是时候。这是一个 固定编程常量 。它是整数值 8:

>>> import stat
>>> stat.ST_MTIME
8

os.stat()returns你要看的结构,看os.stat_result documentation。您的代码忽略了返回的对象,您想将其存储在一个变量中然后使用该变量的属性:

import os
from datetime import datetime

stat_result = os.stat("abc.txt")

print("File size in byte is:", stat_result.st_size)
print("File last modified is:", datetime.fromtimestamp(stat_result.st_mtime))
print("File last accessed is:", datetime.fromtimestamp(stat_result.st_mtime))

stat.ST_* constantsos.stat() returns 的命名元组的索引,但您在这里不需要它们,因为命名元组也支持命名属性。

但是您应该更喜欢使用命名属性,因为您可能会得到 更详细的值stat_result.st_mtime 属性为您提供 stat_result.st_mtime_ns 值除以 10 亿的值,而 stat_result[8]stat_result[stat.ST_MTIME] 为您提供四舍五入到整秒的值:

>>> open("abc.txt", "w").write("Some example text into the file\n")
32
>>> stat_result = os.stat("abc.txt")
>>> stat_result.st_mtime
1629566790.0892947
>>> stat_result.st_mtime_ns
1629566790089294590
>>> stat_result.st_mtime_ns / (10 ** 9)
1629566790.0892947
>>> stat_result[stat.ST_MTIME]
1629566790

使用索引为您提供整数,以便与旧代码向后兼容。