tools.py
1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
from datetime import (
datetime,
date,
time,
)
from decimal import Decimal
#################
# Compare value #
#################
MIDNIGHT_TIME = time(0, 0, 0)
def split_time(t) -> tuple:
if isinstance(t, datetime):
return t.date(), t.time()
return t, MIDNIGHT_TIME
def is_same(a, b) -> bool:
if a == b:
return True
if not (isinstance(a, date) or isinstance(a, datetime)):
return False
date_a, time_a = split_time(a)
date_b, time_b = split_time(b)
if date_a != date_b:
return False
if isinstance(a, date) or isinstance(b, date):
return True
if time_a == time_b:
return True
return False
################
# Plain Object #
################
def date_str(v):
return f'{v.year}-{v.month:02}-{v.day:02}'
def time_str(v):
return f'{v.hour:02}:{v.minute:02}:{v.second:02}'
def datetime_str(v):
s_date = date_str(v)
s_time = time_str(v)
return f'{s_date} {s_time}'
def plain_value(v):
if isinstance(v, str):
return v
if isinstance(v, datetime):
return datetime_str(v)
if isinstance(v, date):
return date_str(v)
if isinstance(v, Decimal):
return float(v)
if isinstance(v, time):
return time_str(v)
return v
def plain_values(d):
r = dict()
for key in d:
v = d[key]
r[str(key)] = plain_value(v)
return r
def update(source: dict, target: dict):
target_update = dict()
log_msg = []
for field in target:
if field not in source:
continue
source_value = source[field]
target_value = target[field]
if not is_same(source_value, target_value):
target_update[field] = source_value
log_source_value = plain_value(source_value)
log_target_value = plain_value(target_value)
log_msg.append('{f} {t} to be {s}'.format(
f=field, t=[log_target_value], s=[log_source_value]))
return target_update, log_msg