Print file age in seconds using Python

Question:

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.

Asked By: Marko

||

Answers:

Use stat.M_TIME to get the last modified time and subtract it from the current time.

http://docs.python.org/library/stat.html

#!/usr/bin/python3 
# -*- coding: utf-8 -*- 
import os, time 

def file_age_in_seconds(filename): 
    try: 
        return int(time.time() - os.path.getmtime(filename)) 
    except: 
        #on any failure condition 
        return -1  
 
filename = "/tmp/foobar.txt" 

print(file_age_in_seconds(filename))   #prints -1 
f = open(filename, 'w') 
f.write("this is a line") 
f.close()

print(file_age_in_seconds(filename))   #prints 0 
time.sleep(4.2) 
print(file_age_in_seconds(filename))   #prints 4 
Answered By: Deleted

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

import os
st=os.stat('/tmp')    
mtime=st.st_mtime
print(mtime)
# 1325704746.52

Or, equivalently, using os.path.getmtime:

print(os.path.getmtime('/tmp'))
# 1325704746.52

If you want a datetime.datetime object:

import datetime         
print("mdatetime = {}".format(datetime.datetime.fromtimestamp(mtime)))
# mdatetime = 2012-01-04 14:19:06.523398

Or a formated string using 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

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”.

Answered By: unutbu

Another approach (I know I wasn’t the first answer but here goes anyway):

import time, os, stat

def file_age_in_seconds(pathname):
    return time.time() - os.stat(pathname)[stat.ST_MTIME]
Answered By: Ray Toal

The accepted answer does not actually answer the question, it just gives the answer for last modification time. For getting the file age in seconds, minutes or hour you can do this.

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
Answered By: cieunteung

This will do in days, can be modified for seconds also:

#!/usr/bin/python

import os
import datetime
from datetime import date

t1 = os.path.getctime("<filename>")

now = datetime.datetime.now()

Y1 = int(datetime.datetime.fromtimestamp(int(t1)).strftime('%Y'))
M1 = int(datetime.datetime.fromtimestamp(int(t1)).strftime('%m'))
D1 = int(datetime.datetime.fromtimestamp(int(t1)).strftime('%d'))

date1 = date(Y1, M1, D1)

Y2 = int(now.strftime('%Y'))
M2 = int(now.strftime('%m'))
D2 = int(now.strftime('%d'))

date2 = date(Y2, M2, D2)

diff = date2 - date1

days = diff.days
Answered By: Aerogon

You can get it by using OS and datetime lib in python:

import os
from datetime import datetime

def fileAgeInSeconds(directory, filename):
    file = os.path.join(directory, filename)
    if os.path.isfile(file):
        stat = os.stat(file)
        try:
            creation_time = datetime.fromtimestamp(stat.st_birthtime)
        except AttributeError:
            creation_time = datetime.fromtimestamp(stat.st_mtime)
        curret_time = datetime.now()
        duration = curret_time - creation_time
        duration_in_s = duration.total_seconds()
        return duration_in_s
    else:
        print('%s File not found' % file)
        return 100000

#Calling the function

dir=/tmp/
fileAgeInSeconds(dir,'test.txt')
Answered By: Vivek Kumar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.