【问题标题】:Mismatch between file creation time and current time in PythonPython中文件创建时间和当前时间不匹配
【发布时间】:2019-05-17 13:40:26
【问题描述】:

为什么文件创建时间小于创建前测量的时间?

import os, time

before_creation = time.time()

with open('my_file', 'w') as f:
    f.write('something')

creation_time = os.stat('my_file').st_ctime

print(before_creation)  # 1545031532.8819697
print(creation_time)    # 1545031532.8798425
print(before_creation < creation_time)  # False

编辑操作系统是 Linux

【问题讨论】:

标签: python linux python-3.x file time


【解决方案1】:
  • 因为 OS 模块来自 CPython,最初是为 python 设计的 2.x 版本。如果您在 2.7 版本中运行代码,它会为 before_creation 和 creation_time 返回相同的值。因为,结果是 仅在 2.x 版本中限制为 2 位小数。
    eg., 1545073155.03
  • 另外,您必须注意,当您执行 print(os.stat('my_file')) 时,我们会得到
    posix.stat_result(st_mode=33204, st_ino=12, st_dev=1792, st_nlink=1, st_uid=488, st_gid=487, st_size=0, st_atime=1545073155, st_mtime=1545073155, st_ctime=1545073155)
  • 如果你这样做了 print(os.stat('my_file')[9]) 我们得到1545073155
    解决方案,您可能必须使用 time.time() 来获取时间 创建。
    考虑到这一点,在 st_ctime 的 int 到 float 的转换。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-05
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    相关资源
    最近更新 更多