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

Python实现脚本当前与上次执行时间记录的日志文件

Python 实现执行时间日志记录(生成含上次/当前时间戳的DataFrame)

原代码的问题出在没有持久化存储上次执行的时间,而且函数逻辑完全没处理Last Datetime和DateTime的对应关系,自然实现不了你要的效果:首次执行Last Datetime为NaN,后续执行自动填充上次的DateTime。

要解决这个问题,核心是每次运行脚本时读取之前保存的日志文件(如果存在),用上次的时间作为本次的Last Datetime,再记录当前时间,最后把更新后的记录存回文件,供下次使用。

修改后的完整代码

import datetime
import pandas as pd
import os

# 日志文件路径,用来持久化保存执行记录
LOG_FILE = "execution_log.csv"

def update_execution_log():
    # 获取当前时间,格式和你预期的示例一致
    current_time = datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S")
    
    if os.path.exists(LOG_FILE):
        # 非首次执行,读取已有日志
        execution_df = pd.read_csv(LOG_FILE)
        # 取最后一条记录的DateTime作为本次的Last Datetime
        last_run_time = execution_df.iloc[-1]["DateTime"]
        # 构造新的一行记录
        new_record = pd.DataFrame({
            "Last Datetime": [last_run_time],
            "DateTime": [current_time]
        })
        # 合并新记录到原有DataFrame
        execution_df = pd.concat([execution_df, new_record], ignore_index=True)
    else:
        # 首次执行,Last Datetime设为NaN
        execution_df = pd.DataFrame({
            "Last Datetime": [pd.NA],
            "DateTime": [current_time]
        })
    
    # 保存更新后的日志,覆盖原文件
    execution_df.to_csv(LOG_FILE, index=False)
    return execution_df

# 生成你需要的execution_file DataFrame
execution_file = update_execution_log()
print(execution_file)

执行效果

  • 首次运行输出:
Last Datetime             Datetime
0           NaN  2024/05/20 16:10:00
  • 再次运行输出:
Last Datetime             Datetime
0                  NaN  2024/05/20 16:10:00
1  2024/05/20 16:10:00  2024/05/20 16:12:00

关键说明

  1. 用os.path.exists判断是否是首次执行,决定是创建新记录还是追加新记录
  2. 用pd.read_csv和pd.to_csv实现日志的持久化,确保下次运行能获取到上次的时间
  3. 时间格式严格匹配你给出的示例(年/月/日 时:分:秒)
  4. 用pd.NA标记首次执行的空值,比普通NaN更符合pandas的规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 11:57:15