将 datetime.datetime 个对象写入文件

Write datetime.datetime object to a file

问题

我想将一个 datetime.datetime 对象写入文件,因为我的机器人整晚都停机了,我需要它检查从那个时间点到当前消息的所有消息,但我找不到解决方法我可以做到这一点。文件类型并不重要,只要我可以向它写入 datetime.datetime 对象并可以从中读取它(但我更喜欢 JSON,因为我已经有了一个用于写入、读取的系统。 .. 为此)。

尝试过

我尝试将其作为原始 datetime.datetime 写入 JSON 文件,并尝试将其作为原始 datetime.datetime 写入带有 .write() 的 txt 文件,但两者都没有不行,因为他们不接受那种类型。

当前代码

在机器人关闭时:

async for message in channel.history(limit=1):
    lastmsg = message.created_at

jsonhandle.update("last_message", lastmsg, "lastmsg")

调用 on_ready:

last_message = jsonhandle.get("last_message", "lastmsg")

    chistory = await channel.history(after=last_message).flatten()

一种简单的方法是将 datetime 对象格式化为字符串并写入:

import datetime

# Write the datetime
date = datetime.datetime(2021, 3, 28, 18, 37, 4, 127747)
with open(file_name, 'w') as f:
    f.write(date.isoformat())

# Read it back
with open(file_name) as f:
    date = datetime.datetime.fromisoformat(f.read())

在此示例中,文件将包含 2021-03-28T18:37:04.127747

通过在末尾添加 .strftime("%d-%b-%Y (%H:%M:%S.%f)")datetime 对象格式化为字符串。

现在您可以使用 write()

将其保存到任何文件
with open(file_name, 'w') as file:
    file.write(datetime.datetime.now().strftime("%d-%b-%Y (%H:%M:%S.%f)"))

要读取文件,您必须使用 strptime

对其进行解析
with open(file_name, 'r') as file:
    date_time = datetime.datetime.strptime(file.read(), "%d-%b-%Y (%H:%M:%S.%f)")