1

I would like to write a (pandas) DataFrame to a json file. But one of my columns is a date and when I read from the json file the date format is Miliseconds(?)

    from pandas import DataFrame, read_json
    from datetime import date

    A = {'a': [date(2019,1,1),date(2019,1,2),date(2019,1,2)], 'b': [4,5,6]}
    df = DataFrame(A)
    print(df)

    filename = r'C:\temp\Export_DataFrame.json'
    #to json file
    Export = df.to_json(filename)

    #import from json
    df2 = read_json(filename)
    print(df2)

gives me the following result:

                a  b
    0  2019-01-01  4
    1  2019-01-02  5
    2  2019-01-02  6

                   a  b
    0  1546300800000  4
    1  1546387200000  5
    2  1546387200000  6

When reading the json file how do I convert to datetime?

Thx in advance

1 Answer 1

2

Use convert_dates parameter in read_json with specify column name, here a, because not datelike column parsed by default:

convert_dates : bool or list of str, default True

List of columns to parse for dates. If True, then try to parse datelike columns. A column label is datelike if

it ends with '_at',
it ends with '_time',
it begins with 'timestamp',
it is 'modified', or
it is 'date'.

df2 = pd.read_json(filename, convert_dates=['a'])
print(df2)
           a  b
0 2019-01-01  4
1 2019-01-02  5
2 2019-01-02  6
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.