Plot time-of day histogram for array of datetimes
26 views (last 30 days)
Show older comments
How do I create a histogram for an array of datetimes showing the counts of times of day from 00:00 to 24:00. I'd like the bin width to be variable between 1 to 60 minutes.
0 Comments
Accepted Answer
dpb
on 1 Oct 2025 at 19:01
7 Comments
dpb
on 2 Oct 2025 at 15:35
No problem -- I should have recalled the timeofday function; subtracting the base datetime for each day is what it does. Seems like maybe when the datetime class was first introduced it wasn't yet there, maybe, is why I fixated on using the duration class; I don't recall precisely. I do remember there being an Answers Q? quite a long time ago about creating some specialized plots that the poster had initially done with datenum required recasting; maybe that recollection got me sidetracked.
Anyways, glad you looked in more depth on your own...
dpb
about 3 hours ago
Edited: dpb
25 minutes ago
"... have no idea what a class is..."
The object-oriented implementation of data types are classes in MATLAB.
dn=now % get current time as datenum
dt=datetime(dn,'ConvertFrom','datenum') % convert to a datetime variable
t=timeofday(dt) % and get the time of day corresponding
and see what each is in MATLAB
whos
and we see each is a different class; they have different properties and methods specific for what the represent and, in the case of the time-related variables, how they represent time. A datenum is "just" a regular floating point double variable interpreted in a particular way; the integer portion represents the days after the origin reference date and the fractional part the fraction of a day of 24 hours.
datestr(dn)
dayn=floor(dn);
datestr(dayn,'dd=mmm-yyyy HH:MM:SS')
datestr(dn-dayn,'dd=mmm-yyyy HH:MM:SS')
By comparison,
dt-dateshift(dt,'start','day')
returns the same time within the day as the fractional port of the datenum or timeofday function.
As a general rule, the use of datetime and duration classes is the better choice; in particular plotting as here is greatly simplified for time-related axes that have to be manually configured when using datenums because, as shown above, there is no indication that the particular variable is any different than any other double for the generation of the axes as displaying user-interpretable times. You can now see the advantage of having a class that does impart that knowledge.
More Answers (0)
See Also
Categories
Find more on Data Distribution Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!