首页 > 解决方案 > 如何将日期时间保存到 Python 中的文件以用于脚本自动化

问题描述

我正在创建一个脚本,该脚本会定期从服务器上抓取已添加的“新”文件。为此,我希望将我上次执行脚本的日期时间存储在一个文件中,以便脚本可以处理自该日期时间以来的“所有新文件”。最终目标是通过 Windows 任务计划程序定期运行此脚本。

我可以使用下面的代码来做这个的基本版本。但是,我希望有一种更清洁、更短或更稳健的方式来实现这一目标。欢迎任何建议!

import datetime

fmt = "%Y-%m-%d %H:%M:%S"
last_run = ""

# try loading the datetime of the last run, else print warning
try:
    with open("last_run.txt", mode="r") as file:
        last_run = datetime.datetime.strptime(file.read(), fmt)
        print(last_run)
except:
    print("no file available")


# ... run script code using the last_run variable as input ...


# update the script execution time and save it to the file
with open("last_run.txt", mode="w") as file:
    file.write(datetime.datetime.now().strftime(fmt))

标签: pythondatetimeautomation

解决方案


Your solution looks fine.

The only thing that I would like to suggest to take out reading and writing last run time stamp logic in two separate functions and move those two functions in a separate module file. This is same as per suggestion from @Tomalak in the above reply. Below is the example with code.

Module file: last_run.py

import datetime

fmt = "%Y-%m-%d %H:%M:%S"


def get_last_run_time_stamp():
    """
    Get last run time stamp\n
    ====\n
    When this function called\n
    AND  last_run.txt file is present\n
    Then open the file and read the time-stamp stored in it\n
    ====\n
    When this function is called\n
    AND last_run.txt file is not present\n
    Then print the following message on console: "last_run.txt file is not available"\n
    """
    # try loading the datetime of the last run, else print warning
    try:
        with open("last_run.txt", mode="r") as file:
            return datetime.datetime.strptime(file.read(), fmt)
    except:
        # Return with current time-stamp if last_run.txt file is not present
        return datetime.datetime.now().strftime(fmt)


# ... run script code using the last_run variable as input ...

def save_last_run_time_stamp():
    """
    Save last run time stamp\n
    ====\n
    When this function called\n
    AND  last_run.txt file is present\n
    Then Open the file, save it with current time stamp and close the file\n
    ====\n
    When this function called\n
    AND  last_run.txt file is not present\n
    Then Create the file, open the file, save it with current time stamp and close the file\n
    """
    # update the script execution time and save it to the file
    with open("last_run.txt", mode="w") as file:
        current_timestamp = datetime.datetime.now().strftime(fmt);
        file.write(current_timestamp)

Then, below is the file configured and run by schedular:

run_latest_scaped_files.py,

import last_run as lr

last_run = lr.get_last_run_time_stamp()
print(last_run)

# ... run script code using the last_run variable as input ...

lr.save_last_run_time_stamp()

That's it!!!


推荐阅读