Skip to main content
Albero Academy

Structured & Datetime Arrays

Store mixed-type records with structured dtypes, and work with calendar dates using datetime64 and timedelta64.

Chapter 13NumPy14 min readBeginner friendly
  • #NumPy
  • #Datetime
  • #Structured

Arrays don't have to be all-numbers. Structured dtypes let one array hold named fields of different types (like a lightweight table), and datetime64 gives NumPy real calendar arithmetic. Both fill gaps between raw arrays and pandas.

Structured arrays

Define a compound dtype with named fields, then access columns by name:

records in an array
dt = np.dtype([('name', 'U10'), ('age', 'i4'), ('pkg', 'f8')])
people = np.array([('Ana', 23, 6.5), ('Ravi', 25, 8.0)], dtype=dt)
people['name'] # array(['Ana', 'Ravi'])
people['pkg'].mean() # 7.25
people[people['age'] > 24] # filter records like rows

datetime64

NumPy's datetime64 stores dates/times compactly and supports vectorised arithmetic:

dates as data
d = np.array(['2026-01-01', '2026-07-08'], dtype='datetime64[D]')
d # ['2026-01-01' '2026-07-08']
d.astype('datetime64[M]') # truncate to month

Date arithmetic

Subtract dates to get a timedelta64, and add durations to shift dates — all vectorised:

differences & offsets
start = np.datetime64('2026-01-01')
end = np.datetime64('2026-07-08')
end - start # 188 days (timedelta64)
start + np.timedelta64(30, 'D') # 30 days later
(end - start) / np.timedelta64(1, 'W') # duration in weeks

Date ranges

generating dates
np.arange('2026-01', '2026-04', dtype='datetime64[M]')
# ['2026-01' '2026-02' '2026-03']
np.arange('2026-01-01', '2026-01-08', dtype='datetime64[D]') # a week of days

Practice

Build a structured array of a few people (name, age, package) and compute the average package and filter by age. Create two datetime64 dates, find the number of days between them, and generate a monthly date range for a year.

Key takeaways

  1. 01Structured dtypes let one array hold named fields of different types — a lightweight table.
  2. 02Access structured columns by name (arr['field']) and filter records like rows.
  3. 03datetime64 stores dates compactly with a chosen unit (D, M, Y…) and vectorised arithmetic.
  4. 04Subtracting dates yields timedelta64; add timedelta64 to shift dates.
  5. 05np.arange with a datetime64 dtype generates date ranges; pandas builds on all of this.