i think what you are looking for is something like this.
# ---------------------------------------------------------
# d1 and d2 are in degries
def anglediff(d1, d2):
result = abs(d1 - d2) % 360
sign = 1
if not ((d1 - d2 >= 0 and d1 - d2 <= 180) or (d1 - d2 <= -180 and d1 - d2 >= -360)):
sign = -1
if result > 180:
result = 360-result
return result*sign
# -----------------------------------------------------------
and here is a demo blend to show how it is used.
angle-diff.blend (578.9 KB)