比较日期以检查旧文件

18

我想检查一个文件是否比一定时间(例如2天)更旧。

我成功地以这样的方式获得了文件的创建时间:

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

我现在该如何检查这个是否超过2天了?

我使用Linux,但跨平台的解决方案会更好。谢谢!


第三行中的 file 是什么? - Joe
我刚刚删除了一个腐败的文件。 - Stefano
2个回答

31

我知道,这是一个老问题。但当我在寻找类似的东西时,我想到了这个替代方案:

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

1
您可以跳过字符串表示形式的转换:filetime = datetime.fromtimestamp(path.getctime(file)) - Erik Forsberg
@ErikForsberg,太好了!已更新。谢谢! - Eduardo

23
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"

1
+1 我知道这很容易...但是我被数据类型卡住了...非常感谢! :) - Stefano
1
我认为使用timedelta会更加简洁(参考:Eduardo的回答)。 - Alvaro

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接