How plot datetime.time in matplotlib?

浪子不回头ぞ 提交于 2021-01-26 03:54:55

问题


I have two arrays I want to display :

x : [datetime.time(0, 17, 47, 782000), ...ect
y : [1712, 2002, ...ect

I'm trying to convert x to the format used by matplotlib but it never woks

x = [matplotlib.dates.date2num(i) for i in x]

But I get this error

AttributeError: 'datetime.time' object has no attribute 'toordinal'

My problem is linked with the time format : The raw info is like this :

00:04:49.251

Then I convert it

datetime.datetime.strptime(string, "%H:%M:%S.%f").time()

So the type is

<type 'datetime.time'>

回答1:


The problem here is that you specify datetime.time objects which only have the information on the time of day. As Emanuele Paolini points out in their comment, matplotlib expects to have datetime.datetime objects which carry the date in addition to the time.

You may carry out the conversion:

import datetime

my_day = datetime.date(2014, 7, 15)
x_dt = [ datetime.datetime.combine(my_day, t) for t in x ]

Now you may use x_dt with the plot function.

The downside of this approach is that you may get the date somewhere on your plot, but that can be tackled by changing the label settings.




回答2:


I believe you are using the time module where as it expects a datetime object.

for the error you can use something like this, ( I am 99% sure this should solve the error)

from datetime import datetime

dates.append(datetime.strptime(row[5], "%a, %d %b %Y %H:%M:%S %Z"))


来源:https://stackoverflow.com/questions/24757178/how-plot-datetime-time-in-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!