How to convert all the string dates to Timestamp while loading a JSON?
The solution should work for keys and list of values as well. Solutions mentioned over here How to convert to a Python datetime object with JSON.loads? only work for string values and don't convert all the cases for the example json string given below:
{
"single_date": "10/02/2020",
"list_of_dates": ["10/03/2020", "10/04/2020"],
"10/05/2020": "date_as_key",
"nested":{
"single_date": "10/02/2020",
"list_of_dates": ["11/03/2020", "11/04/2020"],
"11/05/2020": "date_as_key"
}
}
Expected Output:
{
'single_date': Timestamp('2020-10-02 00:00:00'),
'list_of_dates': [Timestamp('2020-10-03 00:00:00'), Timestamp('2020-10-04 00:00:00')],
Timestamp('2020-10-05 00:00:00'): 'date_as_key',
'nested': {
'single_date': Timestamp('2020-10-02 00:00:00'),
'list_of_dates': [Timestamp('2020-11-03 00:00:00'), Timestamp('2020-11-04 00:00:00')],
Timestamp('2020-11-05 00:00:00'): 'date_as_key'
}
}
Update:
In the output Timestamp is the pandas timestamp but other datetime objects would work too. So, alternate output can also be:
{
'single_date': datetime.datetime(2020, 10, 2, 0, 0),
'list_of_dates': [datetime.datetime(2020, 10, 3, 0, 0),datetime.datetime(2020, 10, 4, 0, 0)],
datetime.datetime(2020, 10, 5, 0, 0): 'date as key',
'nested': {
'single_date': datetime.datetime(2020, 10, 2, 0, 0),
'list_of_dates': [datetime.datetime(2020, 11, 3, 0, 0),datetime.datetime(2020, 11, 4, 0, 0)],
datetime.datetime(2020, 11, 5, 0, 0): 'date as key'
}
}