Skip to content

Commit 401fb87

Browse files
committed
add datetime, time parsing
change to object
1 parent f0bb08d commit 401fb87

File tree

2 files changed

+52
-11
lines changed

2 files changed

+52
-11
lines changed

pymysqlreplication/packet.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -164,11 +164,8 @@ def parse_opaque(data: bytes):
164164
if type_ in [FIELD_TYPE.NEWDECIMAL, FIELD_TYPE.DECIMAL]:
165165
return decode_decimal(data)
166166
elif type_ in [FIELD_TYPE.TIME, FIELD_TYPE.TIME2]:
167-
# TO-DO: parse decode_TIME
168-
decode_decimal(data)
169-
return None
167+
return decode_time(data)
170168
elif type_ in [FIELD_TYPE.DATE, FIELD_TYPE.DATETIME, FIELD_TYPE.DATETIME2]:
171-
# TO-DO: parse decode_DATETIME
172169
return decode_datetime(data)
173170
else:
174171
return data.decode(errors="ignore")

pymysqlreplication/util/bytes.py

Lines changed: 51 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import datetime
12
import decimal
23
import struct
34
import sys
@@ -97,13 +98,56 @@ def decode_decimal(data: bytes):
9798

9899

99100
def decode_time(data: bytes):
100-
# TO-DO
101-
pass
102-
103-
104-
def decode_datetime(data: bytes):
105-
# TO-DO
106-
pass
101+
v = parse_int64(data)
102+
103+
if v == 0:
104+
return datetime.time(hour=0, minute=0, second=0)
105+
106+
sign = ""
107+
if v < 0:
108+
sign = "-"
109+
v = -v
110+
111+
int_part = v >> 24
112+
hour = (int_part >> 12) % (1 << 10)
113+
min = (int_part >> 6) % (1 << 6)
114+
sec = int_part % (1 << 6)
115+
frac = v % (1 << 24)
116+
return datetime.time(hour=hour, minute=min, second=sec, microsecond=frac)
117+
118+
119+
def decode_datetime(data):
120+
v = parse_int64(data)
121+
122+
if v == 0:
123+
# datetime parse Error
124+
return "0000-00-00 00:00:00"
125+
126+
if v < 0:
127+
v = -v
128+
129+
int_part = v >> 24
130+
ymd = int_part >> 17
131+
ym = ymd >> 5
132+
hms = int_part % (1 << 17)
133+
134+
year = ym // 13
135+
month = ym % 13
136+
day = ymd % (1 << 5)
137+
hour = hms >> 12
138+
minute = (hms >> 6) % (1 << 6)
139+
second = hms % (1 << 6)
140+
frac = v % (1 << 24)
141+
142+
return datetime.datetime(
143+
year=year,
144+
month=month,
145+
day=day,
146+
hour=hour,
147+
minute=minute,
148+
second=second,
149+
microsecond=frac,
150+
)
107151

108152

109153
def parse_int16(data: bytes):

0 commit comments

Comments
 (0)