如果旧文件足够老,我需要我的脚本来下载新文件.我以秒为单位设置文件的最大年龄.因此,我将使用我的脚本编写回到正轨,我需要示例代码,其中文件年龄以秒为单位打印出来.
unu*_*tbu 37
这显示了如何查找文件(或目录)的上次修改时间:
import os
st=os.stat('/tmp')
mtime=st.st_mtime
print(mtime)
# 1325704746.52
Run Code Online (Sandbox Code Playgroud)
或者,等效地,使用os.path.getmtime:
print(os.path.getmtime('/tmp'))
# 1325704746.52
Run Code Online (Sandbox Code Playgroud)
如果需要datetime.datetime对象:
import datetime
print("mdatetime = {}".format(datetime.datetime.fromtimestamp(mtime)))
# mdatetime = 2012-01-04 14:19:06.523398
Run Code Online (Sandbox Code Playgroud)
或者使用time.ctime格式化的字符串
import stat
print("last accessed => {}".format(time.ctime(st[stat.ST_ATIME])))
# last accessed => Wed Jan 4 14:09:55 2012
print("last modified => {}".format(time.ctime(st[stat.ST_MTIME])))
# last modified => Wed Jan 4 14:19:06 2012
print("last changed => {}".format(time.ctime(st[stat.ST_CTIME])))
# last changed => Wed Jan 4 14:19:06 2012
Run Code Online (Sandbox Code Playgroud)
虽然我没有展示它,但是找到所有这些方法的访问时间和更改时间都是等价的.只需点击链接并搜索"atime"或"ctime"即可.
Ray*_*oal 21
另一种方法(我知道我不是第一个答案,但无论如何都是这样):
import time, os, stat
def file_age_in_seconds(pathname):
return time.time() - os.stat(pathname)[stat.ST_MTIME]
Run Code Online (Sandbox Code Playgroud)
cie*_*ung 11
接受的答案实际上并没有回答问题,它只是给出最后修改时间的答案。要以秒、分钟或小时为单位获取文件年龄,您可以执行此操作。
import os, time
def file_age(filepath):
return time.time() - os.path.getmtime(filepath)
seconds = file_age('myFile.txt') # 7200 seconds
minutes = int(seconds) / 60 # 120 minutes
hours = minutes / 60 # 2 hours
Run Code Online (Sandbox Code Playgroud)