Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas.to_json output date format in specific form

The original form of date in dataframe is:

Date                                                                   
2018-09-17          12.83  12.92  12.38  12.65         12.65  1937329.0
2018-09-10          12.92  13.12  12.81  12.83         12.83  1150470.0

After converted to json, df.to_json(orient='index',date_format='iso') it looks like this:

"2018-09-17T00:00:00Z":{"

any way to fix this?

like image 935
Chan Austin Avatar asked Oct 10 '18 00:10

Chan Austin


People also ask

How do I change the date format from YYYY MM DD in pandas?

Please notice that you can also specify the output date format other than the default one, by using the dt. strftime() method. For example, you can choose to display the output date as MM/DD/YYYY by specifying dt. strftime('%m/%d/%Y') .

How do I change pandas datetime format?

Use astype() to Change datetime to String Format You can use this if the date is already in the format you want it in string form. The below example returns the date as a string with format %Y/%m/%d . dtype of column ConvertedDate will be object ( string ). Yields below output.

Which function to change the date format in pandas DataFrame?

Function usedstrftime() can change the date format in python.


2 Answers

The easiest fix is to first convert your datetime series to an object dtype series of strings:

df['Date'] = df['Date'].dt.strftime('%Y-%m-%d')

I advise you only do this as a final step prior to json conversion, as you lose benefits of vectorised computations and likely will see less efficient memory usage.

like image 104
jpp Avatar answered Oct 22 '22 18:10

jpp


the first one is in case you get an error in this part ".dt.strftime('%m-%d-%Y')"

df['date'] = pd.to_datetime(df['date'], errors='coerce')
df['date'] = df['date'].dt.strftime('%m-%d-%Y')
like image 35
TRAPSTEP DUCK Avatar answered Oct 22 '22 17:10

TRAPSTEP DUCK