I am a python beginner, currently working on automation. So I am trying to compare two dictionaries. First if key from master is in slave. If it is, compare dates (value[1]) from those keys, check if date from master is newer and print value[0] from master. I am able to format date for comparison, but I have no idea how to access slave values after checking which key is present on both even to print them.
master = {"test1": ("123", "2022-02-14T21:50:03.943943Z"), "test2": ("456", "2022-02-14T21:50:03.183617Z"), "test3": ("789", "2022-02-4T21:50:03.183617Z")}
slave = {"test1": ("123", "2022-02-14T08:14:47.850537Z"), "test2": ("456", "2022-02-14T14:32:08.988684Z")}
date_format = "%Y-%m-%dT%H:%M:%S.%f%z"
for key, value in master.items():
if key in slave:
print(datetime.datetime.strptime(value[1], date_format))
print(datetime.datetime.strptime(slave[value[1]], date_format))
CodePudding user response:
You need to call slave
and access the element referenced by the same key that you are checking there exists, and if it does, it is, of course, the same as the one in master
, and that you defined as key
at the beginning of the for loop
. In this way, you get the tuple, from which you want to extract the second element, i.e. the timestamp, for the comparison purpose.
import datetime
master = {"test1": ("123", "2022-02-14T21:50:03.943943Z"), "test2": ("456", "2022-02- 14T21:50:03.183617Z"), "test3": ("789", "2022-02-14T21:50:03.183617Z")}
slave = {"test1": ("123", "2022-02-14T08:14:47.850537Z"), "test2": ("456", "2022-02-14T14:32:08.988684Z")}
date_format = "%Y-%m-%dT%H:%M:%S.%fZ"
for key, value in master.items():
if key in slave.keys():
master_tmsp = datetime.datetime.strptime(value[1].replace(" ",""), date_format)
slave_tmsp = datetime.datetime.strptime(slave[key][1].replace(" ",""), date_format)
if master_tmsp > slave_tmsp:
print(master_tmsp)
I had to include .replace(" ", "")
to remove spaces from the timestamp strings. I didn't know if this was a typo or you're getting data in this way.