Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python error : TypeError: Object of type 'Timestamp' is not JSON serializable'

I have a Dataframe that has a time stamp column of type 'datetime64[ns]'. When I try to insert it to Salesforce platform get an error 'TypeError: Object of type 'Timestamp' is not JSON serializable'. How could I change this timestamp column to have it updated properly. Given below is the view of the 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

Datatype for each of these 4 columns:

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

Could anyone assist on this. Thanks.

like image 960
dark horse Avatar asked May 18 '18 05:05

dark horse


People also ask

How do I fix the object of type datetime is not JSON serializable?

The Python "TypeError: Object of type datetime is not JSON serializable" occurs when we try to convert a datetime object to a JSON string. To solve the error, set the default keyword argument to str in your call to the json. dumps() method.

How do you serialize a datetime object in Python?

Serialize datetime by converting it into String You can convert dateTime value into its String representation and encode it directly, here you don't need to write any encoder. We need to set the default parameter of a json. dump() or json. dumps() to str like this json.

What is JSON serialization?

Serialization is the process of converting . NET objects such as strings into a JSON format and deserialization is the process of converting JSON data into . NET objects.


2 Answers

You can try convert datetime to string:

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

Or:

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
like image 122
jezrael Avatar answered Oct 05 '22 11:10

jezrael


If you get an error TimeStamp has no attribute as "astype(str)", you can try, for example, str(timeseries.index[0]). This will convert the timestamp into a string that can then be serialized.

like image 23
Muhammad Ali Avatar answered Oct 05 '22 11:10

Muhammad Ali