You're getting the "Object of type datetime is not JSON serializable" error because the json library doesn't know how to convert a Python datetime object into a string format that JSON understands.
You need to convert the datetime object to a string, preferably in ISO 8601 format, before trying to serialize it. Your example item shows exactly this: "index_timestamp":"2025-06-04 19:16:55.123456+00:00".
Here's how to fix it in your nowyArtykul dictionary creation:
import json
import os
from datetime import datetime, timezone # Import timezone
# Assume SPIS_ARTYKULOW and logger are defined elsewhere
# SPIS_ARTYKULOW = 'articles.json'
# import logging
# logger = logging.getLogger(__name__)
# logging.basicConfig(level=logging.DEBUG) # Example logger setup
def dodajAdresArtykulu(urlArtykulu):
# Initialize the list if the file doesn't exist or is empty
if not os.path.exists(SPIS_ARTYKULOW) or os.path.getsize(SPIS_ARTYKULOW) == 0:
spisArtykulow = []
else:
try:
with open(SPIS_ARTYKULOW, 'r', encoding='utf-8') as sp: # Always good to specify encoding
spisArtykulow = json.load(sp)
except json.JSONDecodeError:
logger.error(f"Error decoding JSON from {SPIS_ARTYKULOW}. Initializing as empty list.")
spisArtykulow = [] # Or handle error appropriately
# Check if the article already exists
# Make sure to access the 'url' key in each dictionary
artykulIstnieje = any(artykul.get("url") == urlArtykulu for artykul in spisArtykulow)
if not artykulIstnieje:
logger.debug(f"Dodaję nowy adres do bazy ({urlArtykulu})")
# Get current UTC time
now_utc = datetime.now(timezone.utc)
# Format the timestamp to match your example (space instead of 'T')
# If 'T' is acceptable, you can use: now_utc.isoformat()
# Your example: "2025-06-04 19:16:55.123456+00:00"
timestamp_str = now_utc.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3] # strftime for microseconds gives 6 digits
# so [:-3] to get milliseconds if desired,
# or keep all 6 if that's what .123456 means.
# For full microsecond precision:
timestamp_str = now_utc.strftime('%Y-%m-%d %H:%M:%S.%f') + now_utc.strftime('%z')
# A simpler way if your Python version formats %z nicely, or to match exactly +00:00 for UTC:
timestamp_str = f"{now_utc.strftime('%Y-%m-%d %H:%M:%S.%f')}{now_utc.strftime('%z')[:3]}:{now_utc.strftime('%z')[3:]}"
# Even simpler for UTC to match +00:00
timestamp_str = now_utc.strftime('%Y-%m-%d %H:%M:%S.%f') + "+00:00"
nowyArtykul = {
"url": urlArtykulu,
# Convert datetime object to string
"index_timestamp": timestamp_str,
"title": "",
"text": "",
# If 'date' is also a datetime, format it too (e.g., YYYY-MM-DD)
# "date": now_utc.strftime('%Y-%m-%d'),
"date": "", # Assuming it's an empty string or a simple date string
"tags": ""
}
spisArtykulow.append(nowyArtykul)
# Write the updated list back to the file
with open(SPIS_ARTYKULOW, 'w', encoding='utf-8') as sp:
json.dump(spisArtykulow, sp, indent=4, ensure_ascii=False)
else:
logger.debug(f"Adres już w bazie ({urlArtykulu})")
# --- Example Usage (assuming logger and SPIS_ARTYKULOW are set up) ---
# For demonstration, let's set them up minimally:
import logging
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
SPIS_ARTYKULOW = 'spis_artykulow.json'
# Create an empty file or a file with an empty list for the first run
if not os.path.exists(SPIS_ARTYKULOW):
with open(SPIS_ARTYKULOW, 'w', encoding='utf-8') as f:
json.dump([], f)
if __name__ == '__main__':
dodajAdresArtykulu("https://example.com/article1")
dodajAdresArtykulu("https://example.org/another")
dodajAdresArtykulu("https://example.com/article1") # Test duplicate
Key changes and explanations:
from datetime import datetime, timezone: We need timezone to correctly create a timezone-aware datetime object for UTC.
now_utc = datetime.now(timezone.utc): Creates a datetime object representing the current time in UTC.
timestamp_str = now_utc.strftime('%Y-%m-%d %H:%M:%S.%f') + "+00:00":
now_utc.strftime('%Y-%m-%d %H:%M:%S.%f') formats the datetime object into a string like "2023-10-27 15:30:45.123456".
+ "+00:00" appends the UTC offset string to match your desired format.
- Note on Microseconds vs. Milliseconds:
.%f gives 6 digits for microseconds. If you strictly need 3 digits for milliseconds (as in .123 from .123456), you'd slice the string: now_utc.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]. Your example has 6 digits (.123456), so %f is correct.
"index_timestamp": timestamp_str,: Assign the formatted string to the dictionary.
"date": "": If this field is also meant to store a date (e.g., publication date of the article), and you have it as a datetime.date or datetime.datetime object, you'll need to format it to a string as well (e.g., your_date_object.strftime('%Y-%m-%d') or your_date_object.isoformat()).
encoding='utf-8': Added to open() calls. It's good practice for handling various characters.
- Error Handling for
json.load: Added a try-except block for json.JSONDecodeError in case the file is corrupted or empty, which would cause json.load to fail.
- Checking
artykul.get("url"): Using .get("url") is safer than artykul.url (which assumes artykul is an object with an attribute url) or artykul["url"] (which would raise a KeyError if "url" is missing).
- Initial File Creation: The example usage shows how to create an empty JSON array
[] in the file if it doesn't exist, so json.load() doesn't fail on an completely empty file. Also handled the case where the file exists but is empty (size 0).
With these changes, the datetime object will be converted to a JSON-compatible string format before json.dump attempts to serialize it.