I am trying to look in current directory for all files that changed in x
amount of minutes. x
will be a command line argument given by user when running the script.
I am having issues converting the command line argument into the appropriate number of seconds:
Here is what I have
import os,sys,time
var = int(sys.argv[1])
past = time.time() - var * 60
result = []
dir = os.getcwd()
for p, ds, fs in os.walk(dir):
for fn in fs:
filepath = os.path.join(p, fn)
status = os.stat(filepath).st_mtime
if os.path.getmtime(filepath) >= past:
result.append(filepath)
print result
This seems to work OK but I don't understand how time works. If the user inputs 5 minutes then I multiply 5 * 60 which gives 300 - this compares then again the status and reports back.
Is this correct?
答案 0 :(得分:1)
Regarding the I don't understand how time works
, please refer to the documentation:
time.time()
: Return the time in seconds since the epoch as a floating point number.os.path.getmtime()
: The return value is a number giving the number of seconds since the epoch (see the time module).So what the program is doing is substract from current time in seconds an amount of seconds and then check if there's a file that was modified after that (os.path.getmtime(filepath) >= past
).
答案 1 :(得分:0)
This is correct, time.time()
will give you a Unix timestamp which means how many seconds have elapsed since Jan 01 1970.
There for you can take time.time() - <seconds>
.
But to do this you need to multiply minutes
given by the user with 60 seconds
and subtract that from time.time()
. All this you've done already.
1447328031 == 2015-11-12 12:34
Subtract 5*60 from that and you have five minutes in the past.
Another method is to use strptime
that can take a human readable time and convert that into a timestamp that you can work with.
from time import strptime
past_struct = strptime("2015-11-12 12:24:00", "%Y-%m-%d %H:%M:%S")
past = mktime(past_struct)
Which would give you the option to do python myscript.py "2015-11-12 12:24:00"
.