Search code examples
pythonjsontimestamptruncate

Python - Truncate a timestamp in json array


Giving the following json array:

[
{
    "2020-02-03T00:04:11.000Z": {
        "USD": [
            0.38449135,
            422507.831002123,
            0
        ]
    },
    "2020-02-04T00:04:08.000Z": {
        "USD": [
            0.39151832,
            390909.273872433,
            0
        ]
    },
    "2020-02-05T00:04:16.000Z": {
        "USD": [
            0.40914842,
            498653.042530699,
            0
        ]
    }
]

I need to remove the minutes, seconds and milliseconds of the key value.

As you can see, the key values are different per item.

Result should be:

[
{
    "2020-02-03": {
        "USD": [
            0.38449135,
            422507.831002123,
            0
        ]
    },
    "2020-02-04": {
        "USD": [
            0.39151832,
            390909.273872433,
            0
        ]
    },
    "2020-02-05": {
        "USD": [
            0.40914842,
            498653.042530699,
            0
        ]
    }
]

Additionally, it should be great if the "USD" key could be deleted and the 3 values will move directly to the first level of the date.


Solution

  • One liner below

    data = [
        {
            "2020-02-03T00:04:11.000Z": {
                "USD": [
                    0.38449135,
                    422507.831002123,
                    0
                ]
            },
            "2020-02-04T00:04:08.000Z": {
                "USD": [
                    0.39151832,
                    390909.273872433,
                    0
                ]
            },
            "2020-02-05T00:04:16.000Z": {
                "USD": [
                    0.40914842,
                    498653.042530699,
                    0
                ]
            }
        }
    ]
    short_data = {k[:k.find('T')]: v['USD'] for k, v in data[0].items()}
    print(short_data)
    

    output

    {'2020-02-03': [0.38449135, 422507.831002123, 0], '2020-02-04': [0.39151832, 390909.273872433, 0], '2020-02-05': [0.40914842, 498653.042530699, 0]}