histogram with time bins from datetime vector

datetime, histogram, matplotlib, python

Solution

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)

Problem

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

Original source

Related problems