Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit be16bb4

Browse files
QuLogicmeeseeksmachine
authored andcommitted
Backport PR #18756: FIX: improve date performance regression
1 parent 6010948 commit be16bb4

File tree

1 file changed

+20
-30
lines changed

1 file changed

+20
-30
lines changed

lib/matplotlib/dates.py

Lines changed: 20 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -285,25 +285,6 @@ def get_epoch():
285285
return _epoch
286286

287287

288-
def _to_ordinalf(dt):
289-
"""
290-
Convert :mod:`datetime` or :mod:`date` to the Gregorian date as UTC float
291-
days, preserving hours, minutes, seconds and microseconds. Return value
292-
is a `float`.
293-
"""
294-
# Convert to UTC
295-
tzi = getattr(dt, 'tzinfo', None)
296-
if tzi is not None:
297-
dt = dt.astimezone(UTC)
298-
dt = dt.replace(tzinfo=None)
299-
dt64 = np.datetime64(dt)
300-
return _dt64_to_ordinalf(dt64)
301-
302-
303-
# a version of _to_ordinalf that can operate on numpy arrays
304-
_to_ordinalf_np_vectorized = np.vectorize(_to_ordinalf)
305-
306-
307288
def _dt64_to_ordinalf(d):
308289
"""
309290
Convert `numpy.datetime64` or an ndarray of those types to Gregorian
@@ -428,20 +409,29 @@ def date2num(d):
428409
if hasattr(d, "values"):
429410
# this unpacks pandas series or dataframes...
430411
d = d.values
431-
if not np.iterable(d):
432-
if (isinstance(d, np.datetime64) or
433-
(isinstance(d, np.ndarray) and
434-
np.issubdtype(d.dtype, np.datetime64))):
435-
return _dt64_to_ordinalf(d)
436-
return _to_ordinalf(d)
437412

438-
else:
439-
d = np.asarray(d)
440-
if np.issubdtype(d.dtype, np.datetime64):
441-
return _dt64_to_ordinalf(d)
413+
# make an iterable, but save state to unpack later:
414+
iterable = np.iterable(d)
415+
if not iterable:
416+
d = [d]
417+
418+
d = np.asarray(d)
419+
# convert to datetime64 arrays, if not already:
420+
if not np.issubdtype(d.dtype, np.datetime64):
421+
# datetime arrays
442422
if not d.size:
423+
# deals with an empty array...
443424
return d
444-
return _to_ordinalf_np_vectorized(d)
425+
tzi = getattr(d[0], 'tzinfo', None)
426+
if tzi is not None:
427+
# make datetime naive:
428+
d = [dt.astimezone(UTC).replace(tzinfo=None) for dt in d]
429+
d = np.asarray(d)
430+
d = d.astype('datetime64[us]')
431+
432+
d = _dt64_to_ordinalf(d)
433+
434+
return d if iterable else d[0]
445435

446436

447437
def julian2num(j):

0 commit comments

Comments
 (0)