2

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.

jpp
  • 159,742
  • 34
  • 281
  • 339
Ecaz
  • 35
  • 4
  • 1
    Possible duplicate of [Create a dictionary with list comprehension in Python](https://stackoverflow.com/questions/1747817/create-a-dictionary-with-list-comprehension-in-python) – Mel May 24 '18 at 14:16

2 Answers2

1

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)}]}}
jpp
  • 159,742
  • 34
  • 281
  • 339
  • This is very close! The result is {'Time': datetime.datetime(2015, 6, 27, 15, 1, 9)} so it is literally including datetime.datetime in the value. – Ecaz May 24 '18 at 16:09
  • You can use `datetime.fromtimestamp(i['Time']).strftime('%Y-%m-%d')` if you need a string output. – jpp May 24 '18 at 16:11
1

You could do something like this - assuming your structure only had dictionaries and lists in it. Otherwise you'd likely need to add other cases to those if statements...

from datetime import datetime
def time_converter(data):
    for k, v in data.items():
       if isinstance(v, (dict,)):
           data[k] = time_converter(v)
       elif isinstance(v, (list,)):
           data[k] = [time_converter(item) for item in v]
       elif k.lower() == 'time':
           data[k] = datetime.fromtimestamp(v)
    return data

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

print(time_converter(d))

Note that time_converter is calling itself recursively. Bear in mind that depending on the size and references in the object you pass in (i.e., self referencing, or very large inputs) it's possible that you'll end up with runtime errors. If your data set is relatively manageable and straightforward, this isn't an issue.

chander
  • 1,997
  • 2
  • 16
  • 15