Python,比较2天,大于3天
Python, comparing 2 days, greater than 3 days
我正在尝试从修改日期超过 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)
我收到错误
不可排序的类型:datetime.timedelta() > int()
我不太确定如何获得 numdays 部分,有人有建议吗? TIA
您想将 numdays 设为 timedelta 对象。
numdays = datetime.timedelta(days=3)
所以您现在正在比较两个日期时间对象。
不要使用 datetime.now()
-- 它 returns 当前本地时间作为可能不明确的原始日期时间对象。使用 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)
我正在尝试从修改日期超过 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)
我收到错误 不可排序的类型:datetime.timedelta() > int()
我不太确定如何获得 numdays 部分,有人有建议吗? TIA
您想将 numdays 设为 timedelta 对象。
numdays = datetime.timedelta(days=3)
所以您现在正在比较两个日期时间对象。
不要使用 datetime.now()
-- 它 returns 当前本地时间作为可能不明确的原始日期时间对象。使用 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)