I need my script to download a new file, if the old one is old enough. I set the maximum age of file in seconds. So that I would get back on track with my script writing I need example code, where file age is printed out in seconds.
Advertisement
Answer
This shows how to find a file’s (or directory’s) last modification time:
Here are the number of seconds since the Epoch, using os.stat
JavaScript
x
6
1
import os
2
st=os.stat('/tmp')
3
mtime=st.st_mtime
4
print(mtime)
5
# 1325704746.52
6
Or, equivalently, using os.path.getmtime:
JavaScript
1
3
1
print(os.path.getmtime('/tmp'))
2
# 1325704746.52
3
If you want a datetime.datetime object:
JavaScript
1
4
1
import datetime
2
print("mdatetime = {}".format(datetime.datetime.fromtimestamp(mtime)))
3
# mdatetime = 2012-01-04 14:19:06.523398
4
Or a formated string using time.ctime
JavaScript
1
8
1
import stat
2
print("last accessed => {}".format(time.ctime(st[stat.ST_ATIME])))
3
# last accessed => Wed Jan 4 14:09:55 2012
4
print("last modified => {}".format(time.ctime(st[stat.ST_MTIME])))
5
# last modified => Wed Jan 4 14:19:06 2012
6
print("last changed => {}".format(time.ctime(st[stat.ST_CTIME])))
7
# last changed => Wed Jan 4 14:19:06 2012
8
Although I didn’t show it, there are equivalents for finding the access time and change time for all these methods. Just follow the links and search for “atime” or “ctime”.