Skip to main content
 首页 » 编程设计

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

2025年05月04日33bhlsheji

我有 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* 

请您参考如下方法:

好吧,一个两步的故事让他们的 PLOT 真的很棒

第 1 步:将数据准备为适当的格式

从 datetime 到 matplotlib 约定兼容 float for dates/times


像往常一样,恶魔隐藏在细节中。

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. 

因此,强烈建议重新使用他们“自己的”工具:

from matplotlib import dates as mPlotDATEs   # helper functions num2date() 
#                                            #              and date2num() 
#                                            #              to convert to/from. 

第 2 步:管理轴标签、格式和比例(最小/最大)作为下一个问题

matplotlib 也为这部分提供了支持。

检查 code in this answer for all details