6

I have a vector with dates (datetime) in python. How can I plot a histogram with 15 min bins from the occurrences on this vector?

Here is what I did:

StartTime = []
for b in myEvents:
    StartTime.append(b['logDate'].time())

As you see, I converted the dates into times. (I'm getting myEvents from a mongoDB query)

fig2 = plt.figure()
ax = fig2.add_subplot(111)
ax.grid(True,which='both')
ax.hist(StartTime,100)

The error I get is:

TypeError: can't compare datetime.time to float

I understand the error, but I can't figure out how to fix it.

Thank you very much for your help

askewchan
  • 45,161
  • 17
  • 118
  • 134
otmezger
  • 10,410
  • 21
  • 64
  • 90
  • You have to convert your `time` to a `float` since that's the only thing the histogramming function understands. You may find [this code](http://ubuntuforums.org/showthread.php?t=700216) helpful. – Floris Mar 18 '13 at 13:42
  • Possible duplicate: http://stackoverflow.com/questions/8369584/plot-histogram-of-datetime-time-python-matplotlib – askewchan Mar 18 '13 at 13:43
  • 1
    @askewchan I already read this question, but could not use it – otmezger Mar 18 '13 at 13:45
  • @Floris, thanks for the link... It can't be true that there is no more elegant way of doing this.... Using what you propose, I need to convert the axis later back from ms to HH:MM again... – otmezger Mar 18 '13 at 13:52

1 Answers1

6

If you want to bin by hour, minute, or second, it should be very easy:

ts = np.array([ datetime.time(random.randint(24),*random.randint(60,size=2)) for i in range(100) ])
hist([t.hour for t in ts], bins = 24) # to bin by hour

Furthermore, for fifteen minute bins, but the problem here is now the units are decimal hours:

hist([t.hour + t.minute/60. for t in ts], bins = 24*60/15)
askewchan
  • 45,161
  • 17
  • 118
  • 134