0

I'm trying to pass a date in post request with aiohttp:

import asyncio
import json
from datetime import datetime
from pprint import pprint

import aiohttp

payload = {'key1': 'value1', 'key2': 'value2', 'now': datetime.now()}


async def main():
    async with aiohttp.ClientSession() as session:
        async with session.post('http://httpbin.org/post', json=payload) as resp:
            pprint(await resp.json())


asyncio.run(main())

But all I get is error:

TypeError: Object of type datetime is not JSON serializable

How to fix it?

P.S. I already tried json.dumps. P.P.S. Please don't offer convert now to string. The example above is simplified example.

  • 2
    Time's a tricky subject, and a date can be represented in many ways. Whether you choose a number (e.g. unix timestamp) or a string representation (ISO-8601), you need to make sure it's what the consumer of your API is expecting. What you have is an abstraction of a date and time, which you need to convert to a format that you can output. Why is converting `now`'s value to a string an invalid approach for you? You can even check for any date value by check each entry for `isinstance(value, datetime.date)`, serializing the value if necessary. – Rogue Aug 02 '23 at 16:18
  • 1
    Please have a look at the following related answers: [here](https://stackoverflow.com/a/73161870/17865804), as well as [here](https://stackoverflow.com/a/74333692/17865804) and [here](https://stackoverflow.com/a/73974946/17865804). Simply put, you would have to convert the `date` object into `str`. – Chris Aug 03 '23 at 03:53
  • jsonable_encoder helped. thanks a lot! – Альберт Александров Aug 03 '23 at 08:50

0 Answers0