You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中将Datetime保存到文件以实现脚本自动化

嘿,你的这个增量爬取思路非常实用!用文件记录上次运行时间来筛选新增文件,完全是这类定时任务的标准操作~我来给你几个优化方向,让脚本更简洁、健壮,同时更易维护:

一、精准捕获异常,避免“一刀切”

原来的except:会捕获所有类型的错误(比如文件权限不足、时间格式损坏),很难定位问题。我们可以针对性捕获特定异常,让错误处理更清晰:

import datetime

TIME_FMT = "%Y-%m-%d %H:%M:%S"
last_run = datetime.datetime.min  # 初始化为最早时间,统一后续逻辑

try:
    with open("last_run.txt", "r") as f:
        last_run = datetime.datetime.strptime(f.read().strip(), TIME_FMT)
except FileNotFoundError:
    print("首次运行:未找到上次运行记录文件")
except ValueError:
    print("警告:上次运行记录格式错误,将按首次运行处理")

二、用pathlib简化文件操作(Python3.4+)

pathlib是Python标准库的现代文件路径工具,比传统的open()更直观,处理路径、检查文件存在都更优雅:

from pathlib import Path
import datetime

TIME_FMT = "%Y-%m-%d %H:%M:%S"
last_run_file = Path("last_run.txt")
last_run = datetime.datetime.min

if last_run_file.exists():
    try:
        last_run = datetime.datetime.strptime(last_run_file.read_text().strip(), TIME_FMT)
    except ValueError:
        print("警告:运行记录格式无效,将从头开始处理")
else:
    print("首次运行,无历史记录")

# --- 你的爬取逻辑,使用last_run筛选文件 ---

# 更新运行时间
last_run_file.write_text(datetime.datetime.now().strftime(TIME_FMT))

三、添加日志,适配Windows任务计划

用Windows任务计划运行脚本时,print的内容可能看不到,换成logging模块可以把日志写到文件,方便排查问题:

import logging
from pathlib import Path
import datetime

# 配置日志:同时输出到控制台和文件
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(message)s",
    handlers=[
        logging.FileHandler("crawler.log"),
        logging.StreamHandler()
    ]
)

TIME_FMT = "%Y-%m-%d %H:%M:%S"
last_run_file = Path("last_run.txt")
last_run = datetime.datetime.min

if last_run_file.exists():
    try:
        last_run = datetime.datetime.strptime(last_run_file.read_text().strip(), TIME_FMT)
        logging.info(f"加载上次运行时间:{last_run}")
    except ValueError:
        logging.warning("运行记录格式错误,将按首次运行处理")
else:
    logging.info("首次运行,无历史记录")

# --- 你的爬取逻辑 ---

# 更新运行时间
current_time = datetime.datetime.now().strftime(TIME_FMT)
last_run_file.write_text(current_time)
logging.info(f"本次运行时间已保存:{current_time}")

额外小建议

  1. 指定绝对路径:Windows任务计划的默认工作目录可能不是脚本所在文件夹,建议给last_run.txt和日志文件指定绝对路径(比如Path(__file__).parent / "last_run.txt",__file__代表当前脚本路径)
  2. 避免并发冲突:如果任务计划可能重复触发脚本(比如前一次还没跑完),可以加文件锁(比如用filelock库),防止多个进程同时读写last_run.txt
  3. 用配置文件存储参数:如果后续要调整时间格式、文件路径等,可以把这些参数放到config.json里,更易维护

内容的提问来源于stack exchange,提问作者mfcss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 19:02:36