Harnish Harnish - 5 months ago 9
Python Question

finding the difference between two values of a dictionary inside a list in python

I have a list like

[{'temp': 39.1, 'date': datetime.datetime(2016, 6, 3, 12, 32, 35)}, {'temp': 39.1, 'date': datetime.datetime(2016, 6, 3, 12, 32, 35)}, {'temp': 39.1, 'date': datetime.datetime(2016, 6, 3, 12, 32, 35)}]


I want to iterate the list and check whether the difference between two DateTime objects is 1 using python. I am new to python. Help would be appreciated.

Answer

Hope this helps.

import datetime
d = [{'temp': 39.1, 'date': datetime.datetime(2017, 6, 3, 13, 32, 35)}, {'temp': 39.1, 'date': datetime.datetime(2016, 6, 3, 12, 32, 35)}, {'temp': 39.1, 'date': datetime.datetime(2016, 6, 3, 12, 32, 35)}]

def compare(data, field):
    #the code
    if len(data) <= 1:
        return
    ret = []
    for i, v in enumerate(data):
        try:
            if v[field] - data[i+1][field] > datetime.timedelta(hours = 1):
                ret.append(True)
            else:
                ret.append(False)
        except:
            pass
    return ret

#testing
differences = compare(d, 'date')
print differences
for i, v in enumerate(differences):
    print 'differences[%s] is the difference between d[%s] and d[%s], The difference is: %s or %s'%(i, i, i+1, v, 'Greater than one' if v else 'Less than one')
Comments