Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing dates to check for old files

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!

like image 314
Stefano Avatar asked Sep 15 '11 12:09

Stefano


People also ask

How can I compare two dates?

For comparing the two dates, we have used the compareTo() method. If both dates are equal it prints Both dates are equal. If date1 is greater than date2, it prints Date 1 comes after Date 2. If date1 is smaller than date2, it prints Date 1 comes after Date 2.

How do you compare dates in Python?

Dates can be easily compared using comparison operators (like <, >, <=, >=, !=

How do you compare two dates in if condition Python?

Use the strptime(date_str, format) function to convert a date string into a datetime object as per the corresponding format . For example, the %Y/%m/%d format codes are for yyyy-mm-dd . Use comparison operators (like < , > , <= , >= , != , etc.) to compare dates in Python.

How do I compare two date columns in PySpark?

Using PySpark SQL functions datediff() , months_between() you can calculate the difference between two dates in days, months, and year, let's see this by using a DataFrame example. You can also use these to calculate age.


2 Answers

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."
like image 144
Eduardo Avatar answered Oct 05 '22 07:10

Eduardo


now = time.time()
twodays_ago = now - 60*60*24*2 # Number of seconds in two days
if fileCreation < twodays_ago:
    print "File is more than two days old"
like image 34
Erik Forsberg Avatar answered Oct 05 '22 07:10

Erik Forsberg