【问题标题】:Comparing dates to check for old files比较日期以检查旧文件
【发布时间】:2011-09-15 12:36:44
【问题描述】:

我想检查文件是否早于一定时间(例如 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 是什么?
  • 我刚刚删除的损坏

标签: python time comparison filemtime


【解决方案1】:

我知道,这是一个老问题。但我一直在寻找类似的东西并想出了这个替代解决方案:

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

【讨论】:

  • 您可以跳过与字符串表示的转换:filetime = datetime.fromtimestamp(path.getctime(file))
  • @ErikForsberg,这样更好!更新了它。谢谢!
【解决方案2】:
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 我知道这很容易......但我对数据类型有点困惑......非常感谢! :)
  • 我相信使用 timedelta 会更干净(参考:Eduardo 的回答)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-09
  • 1970-01-01
  • 1970-01-01
  • 2013-01-26
  • 1970-01-01
  • 2013-09-16
  • 2020-04-21
相关资源
最近更新 更多