viktor_dmitry
viktor_dmitry

Reputation: 103

How to convert data column from dataframe to json format?

I have a sample dataframe with data like this:

2019-04-01 11:00:13
2020-09-05 10:19:11
2021-04-06 12:41:34
2020-11-11 10:49:32
2020-04-04 12:53:52

I want to transform it to json, but the format of data changes to:

"2021-04-06T12:50:23.000Z"

I used this code to convert to json:

df.to_json('output/df.json', orient='records', lines=True, date_format='iso')

How can I keep the same formatting as in the dataframe, without the T and the 000Z?

Upvotes: 1

Views: 50

Answers (2)

hd1
hd1

Reputation: 34657

Store the output of df.to_json('output/df.json', orient='records', lines=True, date_format='iso') as out (and I'll send a patch to the pandas pandas to allow this functionality):

[o.strftime('%Y-%m-%d %H:%M:%S') for o in out.values()]

Upvotes: 1

jezrael
jezrael

Reputation: 862511

It is possible, if convert datetimes to strings:

df['date'] = df['date'].astype(str)
j = df.to_json(orient='records', lines=True, date_format='iso')
print (j)
{"date":"2021-04-06 12:50:23"}
{"date":"2020-10-01 10:39:41"}
{"date":"2021-04-06 12:48:34"}
{"date":"2020-10-01 10:39:36"}
{"date":"2021-04-06 12:52:58"}

Upvotes: 1

Related Questions