0

I have a date in my dataframe with format like this

"2018-05-01"
"2018-05-02"
"2018-05-03"

I want to convert the date into something like this in my JSON

"2018-05-01T00:00:00.000Z"
"2018-05-02T00:00:00.000Z"

I had tried using pd.to_datetime(df['date']) but the result is become something like 1523404800000 in my JSON file. What should I do to get a format like "2018-05-02T00:00:00.000Z" in my JSON?

1 Answer 1

1

You are looking for date_format='iso' in df.to_json()

Full example:

import pandas as pd

csvdata = '''\
date
2018-05-01
2018-05-02
2018-05-03'''

fileobj = pd.compat.StringIO(csvdata)
df = pd.read_csv(fileobj, sep='\s+')

# without conversion
print(df.to_json()) 

# with conversion
df['date'] = pd.to_datetime(df['date'])
print(df.to_json()) 

# with conversion and adding date_format = iso
print(df.to_json(date_format='iso'))

Prints:

{"date":{"0":"2018-05-01","1":"2018-05-02","2":"2018-05-03"}}
{"date":{"0":1525132800000,"1":1525219200000,"2":1525305600000}}
{"date":{"0":"2018-05-01T00:00:00.000Z","1":"2018-05-02T00:00:00.000Z","2":"2018-05-03T00:00:00.000Z"}}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks Anton. Works flawlessly. can i convert null values to \u0000 too ?
@Ducker Now that is a harder question. Possibly use some string replace?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.