How do I keep the timezone of my index when serializing/deserializing a Pandas DataFrame using JSON

Pandas will convert everything to UTC when using to_json.

See this example where I change it to Europe/Paris which is UTC+1:

In [1]:
dr = pd.date_range('2016-01-01T12:30:00Z', '2016-02-01T12:30:00Z')
dr = dr.tz_convert('Europe/Paris')
data = np.random.rand(len(dr), 2)
df = pd.DataFrame(data, index=dr, columns=['a', 'b'])

In [2]: df.index[0]
Out[2]: Timestamp('2016-01-01 13:30:00+0100', tz='Europe/Paris', freq='D')

In [3]: df.to_json('test_data_01.json', date_unit='s', date_format='iso')

If I open the test_data_01.json, the first one is "2016-01-01T12:30:00Z".

So when you load the json, localize it to UTC. There's no way to know what tz was used beforehand though:

In [4]:
df2 = pd.read_json('test_data_01.json')
df2.index = df2.index.tz_localize('UTC')

Tags:

Python

Pandas