1

I have this dataframe with start_date and end_date

enter image description here

and when i convert to json using to_json using this line

json_data = df.to_json(orient='records')

now if i print json_data the start_date is getting converted from yyyy-mm-dd to integer format

Please suggest a way so that the date format remains in yyyy-mm-dd format

Mahesh
  • 1,117
  • 2
  • 23
  • 42

2 Answers2

3

Use DataFrame.select_dtypes for datetime columns, convert to format YYYy-MM-DD and last overwrite original data by DataFrame.update:

df.update(df.select_dtypes('datetime').apply(lambda x: x.dt.strftime('%Y-%m-%d')))

Then your solution working correct:

json_data  = df.to_json(orient='records')
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
2

First set the format of your date, then set the date_format to 'iso':

df['start_date'] = pd.to_datetime(df['start_date']).dt.strftime('%Y-%m-%d')
df['end_date'] = pd.to_datetime(df['end_date']).dt.strftime('%Y-%m-%d')
data = df.to_json(orient='records', date_format='iso')
print(data)

[{"start_date":"2020-08-10","end_date":"2020-08-16"}]
NYC Coder
  • 7,424
  • 2
  • 11
  • 24
  • hey, i tried this but there is extra content in the date like `T00:00:00.000Z` ... how can i remove this? I want the final output as `[{"start_date":"2020-08-10","end_date":"2020-08-16"}] ` – Mahesh Aug 24 '20 at 13:47