Python,比较2天,超过3天

时间:2015-09-25 18:23:47

标签: python date comparison

我试图从修改日期大于3天的文件夹中删除文件。

    numdays = 86400 * 3  # Seconds in a day times 3 days
from datetime import datetime
a = datetime.now()
for delete_f in os.listdir(src1):
    file_path = os.path.join(src1, delete_f)
    try:
        if (a - datetime.fromtimestamp(os.path.getmtime(file_path)) >   numdays):

      os.unlink(file_path)
except Exception as e:
    print (e)

我收到错误 unorderable类型:datetime.timedelta()> INT()

我不确定如何获得numdays部分,有人有建议吗? TIA

2 个答案:

答案 0 :(得分:2)

你想让numdays成为timedelta对象。

numdays = datetime.timedelta(days=3)

所以你现在正在比较两个日期时间对象。

答案 1 :(得分:0)

不要使用datetime.now() - 它会将当前本地时间作为可能不明确的天真日期时间对象返回。请改用time.time()

#!/usr/bin/env python
import os
import time

cutoff = time.time() - 3 * 86400 # 3 days ago
for filename in os.listdir(some_dir):
    path = os.path.join(some_dir, filename)
    try:
        if os.path.getmtime(path) < cutoff: # too old
            os.unlink(path) # delete file
    except EnvironmentError as e:
        print(e)

详情请参阅Find if 24 hrs have passed between datetimes - Python

中不应使用datetime.now()的原因

无关:这里基于pathlib的解决方案:

#!/usr/bin/env python3
import time
from pathlib import Path

cutoff = time.time() - 3 * 86400 # 3 days ago
for path in Path(some_dir).iterdir():
    try:
        if path.lstat().st_mtime < cutoff: #NOTE: don't follow symlinks
            path.unlink() # delete old files or links
    except OSError as e:
        print(e)