Matplotlib - 如何将日期从SQLite转换为matplotlib格式?

And*_*dré 0 python matplotlib

我的日期来自一个SQLite表,我需要在matplotlib图形中显示为X.

"125","2013-08-30 13:33:11"
"120","2013-08-29 13:33:11"
"112","2013-08-28 13:33:11"
Run Code Online (Sandbox Code Playgroud)

我需要使用这个日期我:

plt.plot(prices, dates)
Run Code Online (Sandbox Code Playgroud)

如何转换此日期格式以在图中使用它?

最好的祝福,

wfl*_*nny 5

您想将日期转换为datetime对象.为此,请使用datetime.strptime适合您数据的格式的方法.例如,您的数据是所有形式的

'%Y-%m-%d %H:%M:%S'
Run Code Online (Sandbox Code Playgroud)

year-month-day hour:min:sec.因此,尝试类似的东西

import matplotlib.pyplot as plt
from matplotlib.dates import datetime as dt

raw_dates = ["2013-08-30 13:33:11", "2013-08-29 13:33:11", "2013-08-28 13:33:11"]
x = [dt.datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in raw_dates]
y = [125, 120, 112]

plt.plot(x, y)
Run Code Online (Sandbox Code Playgroud)

如果要调整x轴上的值(我认为它们将显示为小时),您可以设置DateFormatter.

import matplotlib.pyplot as plt
from matplotlib.dates import datetime as dt
from matplotlib.dates import DateFormatter

formatter = DateFormatter('%m-%d')

f = plt.figure()
ax = f.add_subplot(111)

raw_dates = ["2013-08-30 13:33:11", "2013-08-29 13:33:11", "2013-08-28 13:33:11"]
x = [dt.datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in raw_dates]
y = [125, 120, 112]
ax.plot(x, y)

ax.xaxis.set_major_formatter(formatter)
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述