Comparing dates to check for old files

若如初见. 提交于 2019-12-04 16:06:53

问题


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!


回答1:


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"



回答2:


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


来源:https://stackoverflow.com/questions/7430928/comparing-dates-to-check-for-old-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!