import datetime
date = datetime.datetime.strptime('2019-04-03', '%Y-%m-%d')
print(date.strftime('%Y-%m-%d'))
输出结果为:2019-04-03
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime
dates = ['2019-04-01', '2019-04-02', '2019-04-03', '2019-04-04', '2019-04-05']
values = [10, 20, 30, 5, 8]
dates = [datetime.datetime.strptime(d, '%Y-%m-%d').date() for d in dates]
fig, ax = plt.subplots()
ax.plot(dates, values)
ax.set_xlim([datetime.date(2019, 4, 1), datetime.date(2019, 4, 5)]) # 设置时间范围
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) # 设置日期格式
plt.show()
这将显示一个正确的x轴,其范围为2019年4月1日至2019年4月5日,日期格式为yyyy-mm-dd。
比较之前和之后的图表,可以看到我们已经成功的修复了x轴上的问题。