Search code examples
pythonpython-3.xdatetimedictionaryunix-timestamp

Convert dictionary key values from UNIX time to human readable time


I have a variable with a dictionary:

EG:

myVariableDictionary = {'result':{'result':[{'Time':1580619600},{'Time':1580619600}]}}

etc.. and I want to convert, in place, the unix timestamp to a human readable timestamp.

If I pull a single key, I can do this with:

placeholderVariable= myVariableDictionary['result']['result'][0]['Time']
myNewTimeVariable = datatime.datatime.fromtimestamp(placeholderVariable)

But I want to do this in-place for ever iteration of the value. The key names are always the same, and are simply nested.


Solution

  • This is one way:

    from datetime import datetime
    
    d = {'result':{'result':[{'Time':1580619600},{'Time':1580619600}]}}
    
    for i in d['result']['result']:
        i['Time'] = datetime.fromtimestamp(i['Time'])
    
    print(d)
    
    {'result': {'result': [{'Time': datetime.datetime(2020, 2, 2, 5, 0)},
                           {'Time': datetime.datetime(2020, 2, 2, 5, 0)}]}}