I have a python program that needs to add an object to a json file. When I send the string over it’s not writing to the file but gives a, object of date time is not serializable. Here’s my code:
subreddit_timestamp = {str(subreddit.display_name) : {"time_last_received" : current_time}}
with open("last_seen.txt", "w") as file:
file.write(json.dumps(subreddit_timestamp))
Let me know if you need anything else to help me figure out this issue
I tried changing the formattings of the subreddit_timestamp variable thinking it was a formatting issue but that didn’t work. I also tried putting preexisting objects into the json file to see if that was an issue, and it wasn’t.
2
Answers
The issue you’re encountering is related to the fact that the current_time value, which is a datetime object, is not serializable by default in JSON. To resolve this issue, you need to convert the datetime object to a serializable format before writing it to the JSON file. You can do this by creating a custom JSON encoder using the default parameter of json.dumps. Here’s how you can modify your code to handle this:
import json
from datetime import datetime
Example current_time, replace with your own datetime object
current_time = datetime.now()
Define a custom JSON encoder to serialize datetime objects
class DateTimeEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, datetime):
return o.isoformat()
return super(DateTimeEncoder, self).default(o)
subreddit_timestamp = {str(subreddit.display_name): {"time_last_received": current_time}}
with open("last_seen.txt", "w") as file:
file.write(json.dumps(subreddit_timestamp, cls=DateTimeEncoder))
This code defines a custom JSON encoder, DateTimeEncoder, which serializes datetime objects as ISO formatted strings. When you use json.dumps, you pass this custom encoder using the cls parameter, ensuring that the datetime object is serialized correctly before writing it to the JSON file.
As the error message implies, you couldn’t serialize datetime object.
Instead you can format it into a string representation.