Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pandas to_json ignoring microseconds

When writing a pandas dataframe to file using to_json, the microseconds seem lost, with only the milliseconds preserved:

import pandas as pd
from datetime import datetime as dt

df = pd.DataFrame( { 'timestamp' : [dt.strptime('2023-09-19 10:10:10.111222', '%Y-%m-%d %H:%M:%S.%f')] } )
print(df)
df.to_json('data.json')
df1 = pd.read_json('data.json')
print(df1)

giving output:

                   timestamp
0 2023-09-19 10:10:10.111222
                timestamp
0 2023-09-19 10:10:10.111

How can I preserve the microseconds?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

By default, pandas.DataFrame.to_json() uses milliseconds as the date unit. You can change the precision with the date_unit argument. The options are ‘s’, ‘ms’, ‘us’, ‘ns’ for second, millisecond, microsecond, and nanosecond respectively.

For your example, change the line writing the data frame to json to:
df.to_json('data.json', date_unit='us')

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading