Print file age in seconds using Python

Each Answer to this Q is separated by one/two green lines.

I need my script to download 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.

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

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]

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

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

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

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

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')


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .