Matplotlib 和 Python:如何从给定字符串格式化日期时间?

fra*_*pps 4 python mysql datetime matplotlib

我想用 matplotlib 绘制一个图,如下所示:

截屏

问题是我从 mySQL 获取数据,因此日期是一个字符串。我想为每个 y 值分配一个日期。当前的日期格式是这样的:Y-M-d h:m:s

你能帮我解决我必须如何将它格式化为有效的日期时间,还是可以在 x 轴上绘制字符串并在 y 轴上浮动?

Mar*_*ans 6

通常最好先将数据转换为datetime格式。然后可以使用 a 对其进行格式化DateFormatter,如下所示:

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

x_orig = ['2015-12-29 15:01:25', '2015-12-29 15:02:08', '2015-12-29 15:02:13', '2015-12-29 15:04:18']
x = [datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in x_orig]
y = ['7.1', '7.4', '9.4', '10.2']

xs = matplotlib.dates.date2num(x)
hfmt = matplotlib.dates.DateFormatter('%Y-%m-%d\n%H:%M:%S')

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.patch.set_facecolor('lightgrey')
ax.xaxis.set_major_formatter(hfmt)
ax.set_title('Titel des Reports')
ax.set_xlabel('datum')
ax.set_ylabel('2MTemperatur')
plt.setp(ax.get_xticklabels(), size=8)
ax.plot(xs, y, linewidth=2)
ax.scatter(xs, y)
plt.grid()
plt.show()
Run Code Online (Sandbox Code Playgroud)

这将为您提供以下信息:

matplotlib 截图