如何使用datetime.time在Python中绘图

如何使用datetime.time在Python中绘图,python,python-2.7,matplotlib,Python,Python 2.7,Matplotlib,我有HH:MM:SS格式的时间戳列表,并希望使用datetime.time绘制一些值。看起来python不喜欢我这样做。有人能帮忙吗 import datetime import matplotlib.pyplot as plt # random data x = [datetime.time(12,10,10), datetime.time(12, 11, 10)] y = [1,5] # plot plt.plot(x,y) plt.show() *TypeError: float()

我有HH:MM:SS格式的时间戳列表,并希望使用datetime.time绘制一些值。看起来python不喜欢我这样做。有人能帮忙吗

import datetime
import matplotlib.pyplot as plt

# random data
x = [datetime.time(12,10,10), datetime.time(12, 11, 10)]
y = [1,5]

# plot
plt.plot(x,y)
plt.show()

*TypeError: float() argument must be a string or a number*
好吧,两步走的故事让他们的情节真的很好

步骤1:将数据准备成适当的格式 从
datetime
到与日期/时间的
matplotlib
约定兼容的
float


像往常一样,魔鬼被隐藏在细节中

matplotlib
日期几乎相等,但不相等:

#  mPlotDATEs.date2num.__doc__
#                  
#     *d* is either a class `datetime` instance or a sequence of datetimes.
#
#     Return value is a floating point number (or sequence of floats)
#     which gives the number of days (fraction part represents hours,
#     minutes, seconds) since 0001-01-01 00:00:00 UTC, *plus* *one*.
#     The addition of one here is a historical artifact.  Also, note
#     that the Gregorian calendar is assumed; this is not universal
#     practice.  For details, see the module docstring.
因此,强烈建议重新使用他们自己的工具:


第2步:作为下一个问题管理轴标签、格式和比例(最小/最大)
matplotlib
也为您带来了这一部分的武器


选中

它在Python 3.5.3和Matplotlib 2.1.0中仍然有效

解决方法是使用
datetime.datetime
对象而不是
datetime.time
对象:

import datetime
import matplotlib.pyplot as plt

# random data
x = [datetime.time(12,10,10), datetime.time(12, 11, 10)]
x_dt = [datetime.datetime.combine(datetime.date.today(), t) for t in x]
y = [1,5]

# plot
plt.plot(x_dt, y)
plt.show()

截止日期部分不应可见。否则,您可以始终使用DateFormatter:

import matplotlib.dates as mdates
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H-%M-%S'))

你确定你正在使用python2吗?是的,我正在python2.7.2上运行相同的代码。你需要在matplot库中使用一个名为“plot_date”的函数。您需要将这些datetime对象转换为matplotlib日期。matplotlib的哪个版本?>>>matplotlib.\uuuuu版本\uuuuuu'1.0.1'>>
import matplotlib.dates as mdates
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H-%M-%S'))