Write datetime.datetime object to a file

Viewed 2204

Problem

I want to write a datetime.datetime object to a file, because my bot is down over night and I need it to check through all messages from that point of time until current messages but I found no solution how I could do this. The File Type doesn't matter as long as I can write the datetime.datetime object to it and can read it from it (but I would prefer JSON as I already got a system for writing, reading,... for this).

Tried

I tried to write it as raw datetime.datetime to a JSON File and tried to write it as raw datetime.datetime to a txt File with .write() which both didn't work because they don't accept that type.

Current code

At shutdown of the bot:

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

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

Called with on_ready:

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

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

Format the datetime object as string by adding .strftime("%d-%b-%Y (%H:%M:%S.%f)") at the end.

Now you can save it to any file using write()

with open(file_name, 'w') as file:
    file.write(datetime.datetime.now().strftime("%d-%b-%Y (%H:%M:%S.%f)"))

for reading the file you have to parse it using strptime

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

A simple way is to format the datetime object as a string and write that:

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())

In this example, the file will contain 2021-03-28T18:37:04.127747.

Related