【问题标题】:Python datetime and json formatPython 日期时间和 json 格式
【发布时间】:2021-01-29 14:58:11
【问题描述】:

我正在针对 REST API 进行编程。我需要在 POST 的正文中发送一些参数:

{
  "contract": {
    "name": "string",
    "beginDate": "2021-01-29T14:49:46.778Z",
    "endDate": "2021-01-29T14:49:46.778Z"
  },
  "pageSize": 0,
  "webhookEndpoint": "string"
}

我的问题是我正在努力将 Python 中的 datetime 抽象转换为 JSON 中的这种奇怪格式。

这是我已经尝试过的:

from requests import post
payload = {
    "contract":{
        "name": fund,
        "startDate": datetime.now() - timedelta(1),
        "endDate": datetime.now()}
    "pageSize": 300
}
headers = {
    "X-SecureConnect-Token": "12345",
    "Content-Type": "application/json-patch+json", #copied from swagger
    "Accept": "text/plain" #copied from swagger, everything works there
}
r = post("https://theapi.com/endpoint",headers=headers,data=payload) #Object of type datetime is not JSON serializable

我已经尝试使用json 模块。我不知道 API 的这种抽象是如何工作的(显然,当您将 JavaScript 日期转换为字符串时会发生什么,我会非常喜欢没有编写解析器的权限)。

【问题讨论】:

    标签: python json python-requests datetime-format


    【解决方案1】:

    它们不是 JSON 可序列化的,因为您将 Python 日期时间对象传递给 JSON,而不是时间的字符串表示形式。

    您可以通过以下方式在解释器中证明这一点:

    >>> from datetime import datetime, timedelta
    
    >>> type(datetime.now() - timedelta(1))
    <class 'datetime.datetime'>
    
    >>> type(datetime.isoformat(datetime.now() - timedelta(1)))
    <class 'str'>
    

    如您所见,您传递的内容属于 datetime.datetime 类。如果你用 datetime.isoformat 包装它,你会得到一个几乎你想要的格式的字符串表示。然后你只需要截断它并将你的祖鲁字母添加到末尾。

    试试这样的:

    from requests import post
    from datetime import datetime, timedelta
    
    
    payload = {
        "contract":{
            "name": fund,
            "startDate": datetime.isoformat(datetime.now() - timedelta(1))[:-3]+'Z',
            "endDate": datetime.isoformat(datetime.now())[:-3]+'Z'},
        "pageSize": 300
    }
    headers = {
        "X-SecureConnect-Token": "12345",
        "Content-Type": "application/json-patch+json", #copied from swagger
        "Accept": "text/plain" #copied from swagger, everything works there
    }
    r = post("https://theapi.com/endpoint",headers=headers,data=payload) #Object of type datetime is not JSON serializable
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-29
      • 1970-01-01
      • 1970-01-01
      • 2011-09-25
      相关资源
      最近更新 更多