【问题标题】:Python error : TypeError: Object of type 'Timestamp' is not JSON serializable'Python 错误:TypeError:'Timestamp' 类型的对象不是 JSON 可序列化的'
【发布时间】:2018-10-28 11:54:19
【问题描述】:

我有一个 Dataframe,其时间戳列的类型为“datetime64[ns]”。当我尝试将其插入 Salesforce 平台时,会收到错误“TypeError: Object of type 'Timestamp' is not JSON serializable”。我如何更改此时间戳列以使其正确更新。下面给出的是 Dataframe 的视图。

Id,Name,Date,Type
1,ProdA,2018-05-18 04:45:08,S
1,ProdB,2018-05-18 02:15:00,S
1,ProdC,2018-05-16 10:20:00,S

这 4 列中每一列的数据类型:

Id                                     object
Name                                   object
Date                           datetime64[ns]
Type                                   object
dtype: object

任何人都可以在这方面提供帮助。谢谢。

【问题讨论】:

    标签: python json pandas datetime


    【解决方案1】:

    如果您收到错误TimeStamp has no attribute as "astype(str)",您可以尝试,例如str(timeseries.index[0])。这会将时间戳转换为可以序列化的字符串。

    【讨论】:

      【解决方案2】:

      您可以尝试将日期时间转换为字符串:

      df['Date'] = df['Date'].astype(str)
      

      或者:

      df['Date'] = df['Date'].dt.strftime('%Y-%m-%d %H:%M:%S')
      
      print (df.dtypes)
      Id      object
      Name    object
      Date    object
      Type    object
      dtype: object
      

      【讨论】:

      • 你将如何对框架中的所有日期列执行此操作?
      猜你喜欢
      • 2018-11-27
      • 2019-07-12
      • 1970-01-01
      • 1970-01-01
      • 2021-03-11
      • 2021-12-24
      • 2019-11-21
      • 2021-11-13
      • 2018-09-22
      相关资源
      最近更新 更多