Q: finding distance between 2 time's

jkv jkv at unixcluster.dk
Sat May 30 06:06:55 EDT 2009


Hi Martin,

What i usally do is to convert the two times to seconds since epoch and
compare the two values in seconds. You can use time.mktime to convert
localtime to seconds since epoch.

I added a few lines to your script, and now it ought to only print files
newer than 3601 seconds (3600 seconds is one hour).
The modification to you script is just some quick code, im pretty sure
on can compress it a bit.

Regards,
Johnny

script:

import os, time

def buildList(directory):
    listing = os.listdir(directory)
    for x in listing:
        x = os.path.join(directory, x)
        if os.path.isdir(x):
            print ('dir -> %s') % x
        if os.path.isfile(x):
            current_time = time.localtime()
            tstF = time.localtime(os.path.getmtime(x))
            #convert the current time to seconds since epoch
            current_epoch=time.mktime(current_time)
            #convert the timestamp on the file to seconds since epoch
            file_epoch = time.mktime(tstF)
            nSize = os.path.getsize(x)
            time_difference = current_epoch - file_epoch
            #if file newer than one hour print a line
            if time_difference < 3601:
              print ('NEW FILE -> %s %d @ %s') % (x, nSize, time.asctime
(tstF))
   return 0

tstN = time.localtime()
print tstN
print "Time now: %s" % time.asctime(tstN)
buildList('/')


martin at hvidberg.net wrote:
> I made this little script (below) to look througt a dir to see if
> there are any files newer than .e.g. 1 hour.
> I have the loop through the dir working and can retreive file time as
> well as present time.
> both time variables are in the format returned by time.localtime()
>
> My question:
> How do I find the difference between such two time variables, to
> calculate the 'age' of the file?
>
> :-) Martin
>
> ------8<------ Code begin -------------
>
> import os, time
>
> def buildList(directory):
>     listing = os.listdir(directory)
>     for x in listing:
>         x = os.path.join(directory, x)
>         if os.path.isdir(x):
>             print ('dir -> %s') % x
>         if os.path.isfile(x):
>             tstF = time.localtime(os.path.getmtime(x))
>             nSize = os.path.getsize(x)
>             print ('fil -> %s %d @ %s') % (x, nSize, time.asctime
> (tstF))
>     return 0
>
> tstN = time.localtime()
> print tstN
> print "Time now: %s" % time.asctime(tstN)
> buildList('C:\Martin\Work\Work_Eclipse\.metadata')
>
>
>   


-- 
Regards,
jkv
http://unixcluster.dk/public.key




More information about the Python-list mailing list