Skip to content

Commit de3d76d

Browse files
committed
refactor mpl_dates_to_datestrings.
1 parent 3359f30 commit de3d76d

File tree

1 file changed

+29
-12
lines changed

1 file changed

+29
-12
lines changed

plotly/matplotlylib/mpltools.py

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -457,22 +457,39 @@ def prep_xy_axis(ax, props, x_bounds, y_bounds):
457457
return xaxis, yaxis
458458

459459

460-
def mpl_dates_to_datestrings(mpl_dates, format_string="%Y-%m-%d %H:%M:%S"):
461-
"""Convert matplotlib dates to formatted datestrings for plotly.
460+
def mpl_dates_to_datestrings(dates, mpl_formatter):
461+
"""Convert matplotlib dates to iso-formatted-like time strings.
462+
463+
Plotly's accepted format: "YYYY-MM-DD HH:MM:SS" (e.g., 2001-01-01 00:00:00)
462464
463465
Info on mpl dates: http://matplotlib.org/api/dates_api.html
464466
465467
"""
466-
try:
467-
date_times = matplotlib.dates.num2date(mpl_dates, tz=pytz.utc)
468-
time_strings = [date_time.strftime(format_string)
469-
for date_time in date_times]
470-
if len(time_strings) > 1:
471-
return time_strings
472-
else:
473-
return time_strings[0]
474-
except TypeError:
475-
return mpl_dates
468+
_dates = dates
469+
470+
# this is a pandas datetime formatter, times show up in floating point days
471+
# since the epoch (1970-01-01T00:00:00+00:00)
472+
if mpl_formatter == "TimeSeries_DateFormatter":
473+
try:
474+
dates = matplotlib.dates.epoch2num(
475+
[date*24*60*60 for date in dates]
476+
)
477+
dates = matplotlib.dates.num2date(dates, tz=pytz.utc)
478+
except:
479+
return _dates
480+
481+
# the rest of mpl dates are in floating point days since
482+
# (0001-01-01T00:00:00+00:00) + 1. I.e., (0001-01-01T00:00:00+00:00) == 1.0
483+
# according to mpl --> try num2date(1)
484+
else:
485+
try:
486+
dates = matplotlib.dates.num2date(dates, tz=pytz.utc)
487+
except:
488+
return _dates
489+
490+
time_stings = [' '.join(date.isoformat().split('+')[0].split('T'))
491+
for date in dates]
492+
return time_stings
476493

477494

478495
DASH_MAP = {

0 commit comments

Comments
 (0)