skip to Main Content

I have this data in Excel File

enter image description here

When read with this logic,

df = pd.read_excel(xls_file_path)
# Convert DataFrame to JSON
json_data = df.to_json(orient='records')
print(json_data)

[{"Name":"Deepak Kalindi","Employee ID":101,"Joining Date":1704153600000,"Leaving Date":null,"Monthly Salary":12000,"Number of full days":27,"Number of half days":2.5,"Number of leaves":1.5,"OT (full Day)":3,"OT (half Day)":2}]

How to get Joining Date as "02-01-2024" in JSON string?

3

Answers


  1. Try this:

    df['Joining Date'] = pd.to_datetime(df['Joining Date'], format='%d-%m-%Y')
    
    Login or Signup to reply.
  2. Try with date_format=iso, see documentation

    json_data = df.to_json(orient='records', date_format='iso')
    print(json_data)
    

    Output:

    [{"Name":"XYZ","Date":"2024-01-02T00:00:00.000Z"}]
    

    Also, you can force your date columns to be string, which will give you the exact output but depending on your end use-case might not be appropriate:

    df['Date'] = df['Date'].astype(str)
    json_data = df.to_json(orient='records')
    print(json_data)
    

    Print:

    [{"Name":"XYZ","Date":"2024-01-02"}]
    
    Login or Signup to reply.
  3. You can simply use dt.strftime:

    jdata = (df.assign(**{'Joining Date': df['Joining Date'].dt.strftime('%d-%m-%Y')})
               .to_json(orient='records', indent=4))
    

    Output:

    >>> jdata
    [
        {
            "Name":"Deepak Kalindi",
            "Employee ID":101,
            "Joining Date":"02-01-2024",
            "Leaving Date":null,
            "Monthly Salary":12000,
            "Number of full days":27,
            "Number of half days":2.5,
            "Number of leaves":1.5,
            "OT (full Day)":3,
            "OT (half Day)":2
        }
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search