python 有哪些方法可以获取到文件的创建时间
阿神
阿神 2017-04-18 10:06:40
[Python讨论组]
import os
import datetime
...
datetime.datetime.fromtimestamp(os.path.getctime(fn))
...
os.rename(old,new)
f = open(old,'a')
...
f.close()

大体代码如上,要实现的效果是当日志创建文件早于一定天数就给日志改名,然后创建新的日志。
现在遇到个问题:

当编写完代码直接运行时,读取文件创建日期时,改名后创建的新文件读出的是老的文件的创建日期。
之后排查问题的时候用pycharm进行代码断点跟踪,刷新目录后读到的创建日期又变成正常的当前日期了。
再之后运行代码也没出现问题。

请问这个是什么原因造成的?或者有什么好的替代方案实现我的需求来规避这种可能出现的异常?

阿神
阿神

闭关修行中......

全部回复(1)
高洛峰
In [3]: os.stat('./sendmail.py')
Out[3]: posix.stat_result(st_mode=33204, st_ino=313029, st_dev=64769L, st_nlink=1, st_uid=500, st_gid=500, st_size=635, st_atime=1480821883, st_mtime=1480821926, st_ctime=1480821926)

st_ctime

import os
def get_create_time(filename):
    return os.stat(filename).st_ctime

update
文档

os.stat(path) 
Perform the equivalent of a stat() system call on the given path. (This function follows symlinks; to stat a symlink use lstat().)

The return value is an object whose attributes correspond to the members of the stat structure, namely:

st_mode - protection bits, 
st_ino - inode number, 
st_dev - device, 
st_nlink - number of hard links, 
st_uid - user id of owner, 
st_gid - group id of owner, 
st_size - size of file, in bytes, 
st_atime - time of most recent access, 
st_mtime - time of most recent content modification, 
st_ctime - platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows) 

可见st_ctime确实可做为created_time, 修改时间取st_mtime

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号