I am getting: Object of type datetime is not JSON serializable
- User
I am getting: Object of type datetime is not JSON serializable
- Assistant
The error:
Object of type datetime is not JSON serializableoccurs because the
jsonmodule doesn't know how to convert adatetimeobject into a JSON-compatible format (like a string) by default.Here are some ways to fix the error:
1. Convert the datetime to a String
Before adding the datetime object to your dictionary, convert it to a string. For example, use the
isoformat()method:from datetime import datetime now_timestamp = datetime.utcnow().isoformat() + "+00:00" item = { "url": "https://example.com", "index_timestamp": now_timestamp, # now a string, not a datetime object "title": "", "text": "", "date": "", "tags": "" }This way, when you call
json.dump(), there is no datetime object to serialize.
2. Use a Custom JSON Encoder
If you want to directly pass datetime objects, you can create a custom JSON encoder that knows how to handle datetime objects:
import json from datetime import datetime class DateTimeEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime): return obj.isoformat() + "+00:00" return super().default(obj) # Example usage: item = { "url": "https://example.com", "index_timestamp": datetime.utcnow(), # still a datetime object "title": "", "text": "", "date": "", "tags": "" } with open('articles.json', 'w') as sp: json.dump(item, sp, cls=DateTimeEncoder, indent=4)This encoder checks if the object is a
datetimeinstance and converts it to a string accordingly.
Update Your Function Example
Using the Conversion Approach (Simpler):
import json import os from datetime import datetime import logging SPIS_ARTYKULOW = 'articles.json' logger = logging.getLogger(__name__) def dodajAdresArtykulu(urlArtykulu): # Initialize the list if the file doesn't exist if not os.path.exists(SPIS_ARTYKULOW): spisArtykulow = [] else: with open(SPIS_ARTYKULOW, 'r') as sp: spisArtykulow = json.load(sp) # Check if the article already exists artykulIstnieje = any(artykul["url"] == urlArtykulu for artykul in spisArtykulow) if not artykulIstnieje: logger.debug(f"Dodać nowy adres do bazy ({urlArtykulu})") nowyArtykul = { "url": urlArtykulu, "index_timestamp": datetime.utcnow().isoformat() + "+00:00", "title": "", "text": "", "date": "", "tags": "" } spisArtykulow.append(nowyArtykul) with open(SPIS_ARTYKULOW, 'w') as sp: json.dump(spisArtykulow, sp, indent=4, ensure_ascii=False) else: logger.debug(f"Adres już w bazie ({urlArtykulu})")Using the Custom Encoder:
import json import os from datetime import datetime import logging SPIS_ARTYKULOW = 'articles.json' logger = logging.getLogger(__name__) class DateTimeEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime): return obj.isoformat() + "+00:00" return super().default(obj) def dodajAdresArtykulu(urlArtykulu): if not os.path.exists(SPIS_ARTYKULOW): spisArtykulow = [] else: with open(SPIS_ARTYKULOW, 'r') as sp: spisArtykulow = json.load(sp) artykulIstnieje = any(artykul["url"] == urlArtykulu for artykul in spisArtykulow) if not artykulIstnieje: logger.debug(f"Dodać nowy adres do bazy ({urlArtykulu})") nowyArtykul = { "url": urlArtykulu, "index_timestamp": datetime.utcnow(), # still a datetime object "title": "", "text": "", "date": "", "tags": "" } spisArtykulow.append(nowyArtykul) with open(SPIS_ARTYKULOW, 'w') as sp: json.dump(spisArtykulow, sp, cls=DateTimeEncoder, indent=4, ensure_ascii=False) else: logger.debug(f"Adres już w bazie ({urlArtykulu})")Either method works. The first method is simpler, while the custom encoder provides more flexibility if you have multiple datetime fields or other non-serializable objects.
Choose the method that best fits your needs, but make sure all datetime objects are converted to strings before writing the data into JSON.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.