Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How plot datetime.time in matplotlib?

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'>
like image 262
Jean Avatar asked Jul 15 '14 11:07

Jean


1 Answers

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.

like image 53
DrV Avatar answered Oct 11 '22 11:10

DrV