Comparing dates to check for old files

Stefano picture Stefano · Sep 15, 2011 · Viewed 26.8k times · Source

I want to check if a file is older than a certain amount of time (e.g. 2 days).

I managed to get the file creation time in such a way:

>>> import os.path, time
>>> fileCreation = os.path.getctime(filePath)
>>> time.ctime(os.path.getctime(filePath))
'Mon Aug 22 14:20:38 2011'

How can I now check if this is older than 2 days?

I work under Linux, but a cross platform solution would be better. Cheers!

Answer

Eduardo picture Eduardo · Aug 8, 2013

I know, it is an old question. But I was looking for something similar and came up with this alternative solution:

from os import path
from datetime import datetime, timedelta

two_days_ago = datetime.now() - timedelta(days=2)
filetime = datetime.fromtimestamp(path.getctime(file_path))

if filetime < two_days_ago:
  print "File is more than two days old."