Skip to content

Commit 77a8e4a

Browse files
committed
Increase performance when casting dates
1 parent c528f50 commit 77a8e4a

File tree

1 file changed

+32
-20
lines changed

1 file changed

+32
-20
lines changed

MySQLdb/times.py

Lines changed: 32 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -48,25 +48,33 @@ def format_TIMESTAMP(d):
4848

4949

5050
def DateTime_or_None(s):
51-
if ' ' in s:
52-
sep = ' '
53-
elif 'T' in s:
54-
sep = 'T'
55-
else:
56-
return Date_or_None(s)
57-
5851
try:
59-
d, t = s.split(sep, 1)
60-
if '.' in t:
61-
t, ms = t.split('.',1)
62-
ms = ms.ljust(6, '0')
52+
if len(s) < 11:
53+
return Date_or_None(s)
6354
else:
64-
ms = 0
65-
return datetime(*[ int(x) for x in d.split('-')+t.split(':')+[ms] ])
66-
except (SystemExit, KeyboardInterrupt):
67-
raise # pragma: no cover
68-
except:
69-
return Date_or_None(s)
55+
micros = s[20:]
56+
57+
if len(micros) == 0:
58+
# 12:00:00
59+
micros = 0
60+
elif len(micros) > 0 and len(micros) < 7:
61+
# 12:00:00.123456
62+
micros = int(micros) * 10 ** (6 - len(micros))
63+
else:
64+
# 12:00:00.123456789
65+
micros = int(micros)
66+
67+
return datetime(
68+
int(s[:4]), # year
69+
int(s[5:7]), # month
70+
int(s[8:10]), # day
71+
int(s[11:13] or 0), # hour
72+
int(s[14:16] or 0), # minute
73+
int(s[17:19] or 0), # second
74+
micros, # microsecond
75+
)
76+
except ValueError:
77+
return None
7078

7179
def TimeDelta_or_None(s):
7280
try:
@@ -107,14 +115,18 @@ def Time_or_None(s):
107115

108116
def Date_or_None(s):
109117
try:
110-
return date(*[ int(x) for x in s.split('-',2)])
111-
except (TypeError, ValueError):
118+
return date(
119+
int(s[:4]), # year
120+
int(s[5:7]), # month
121+
int(s[8:10]), # day
122+
)
123+
except ValueError:
112124
return None
113125

114126
def DateTime2literal(d, c):
115127
"""Format a DateTime object as an ISO timestamp."""
116128
return string_literal(format_TIMESTAMP(d), c)
117-
129+
118130
def DateTimeDelta2literal(d, c):
119131
"""Format a DateTimeDelta object as a time."""
120132
return string_literal(format_TIMEDELTA(d),c)

0 commit comments

Comments
 (0)