Reputation: 291
I've been trying countless times for the past few days and I can't seem to find a solution.
Here's my current code with some comments:
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.dates as mdates
import datetime
import pandas_datareader.data as web
import matplotlib.ticker as ticker
from mpl_finance import candlestick2_ohlc
from matplotlib.dates import (MONDAY, DateFormatter, MonthLocator,
WeekdayLocator, date2num)
# Define start and end date
end = datetime.datetime.now()
start = end - datetime.timedelta(days=63)
# Load data for the specific stock
quotes = web.DataReader('AAPL', 'yahoo', start, end)
quotes['Date'] = quotes.index
# Order the dataframe
quotes = quotes[['Date','Open', 'High', 'Low', 'Close']]
# 2019-09-16 217.729996 220.130005 217.559998 219.899994
fig, ax = plt.subplots()
candlestick2_ohlc( ax,
quotes['Open'],
quotes['High'],
quotes['Low'],
quotes['Close'],
width=0.5,
colorup='g',
colordown='r')
#ax.xaxis.set_major_locator(ticker.MaxNLocator(8))#I was just testing with this
def mydate(x,pos):
try:
a = quotes['Date'][int(x)]
# print(a) --> 2019-11-04 00:00:00
# type(a) --> <class 'pandas._libs.tslibs.timestamps.Timestamp'>
a = pd.to_datetime(a) # doesn't work
return a
except IndexError:
return ''
ax.xaxis.set_major_formatter(ticker.FuncFormatter(mydate))
fig.autofmt_xdate()
fig.tight_layout()
plt.show()
And this is the output:
As you can see, it shows the date like this: 2019-11-04 00:00:00
My goal is to show the date like this:
I have cleaned up the code as much as I could to make it easier to read and understand.
Upvotes: 3
Views: 177
Reputation: 63
to_datetime has been deprecated ...
try using :
a = a.date()
Or
to_pydatetime()
Upvotes: 2
Reputation: 2845
Check the Python documentation on dates:
https://docs.python.org/3.8/library/datetime.html
You are looking for
return '{:%b}'.format(a)
Upvotes: 2