python-3.xpandasdate-formatto-json

Pandas to_json date format is changing


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


Solution

  • 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"}]