繁体   English   中英

Python中文件创建时间与当前时间不匹配

[英]Mismatch between file creation time and current time in Python

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

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

  • 因为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期间可能存在错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM