Python NumPy: How to Generate All Dates for a Month in NumPy
NumPy's datetime64 type combined with np.arange() provides an efficient way to generate date ranges. This approach handles month lengths and leap years automatically without external dependencies.
Basic Date Range Generation
Use np.arange() with datetime64[D] to generate all days in a month:
import numpy as np
# All days of July 2026
dates = np.arange('2026-07', '2026-08', dtype='datetime64[D]')
print(f"Number of days: {len(dates)}") # 31
print(f"First day: {dates[0]}") # 2026-07-01
print(f"Last day: {dates[-1]}") # 2026-07-31
Output:
Number of days: 31
First day: 2026-07-01
Last day: 2026-07-31
Understanding the Syntax
import numpy as np
# np.arange(start, stop, dtype)
# - Start: First month (inclusive)
# - Stop: Next month (exclusive)
# - dtype: 'datetime64[D]' for daily resolution
dates = np.arange('2026-07', '2026-08', dtype='datetime64[D]')
print(dates[:5])
Output:
['2026-07-01' '2026-07-02' '2026-07-03' '2026-07-04' '2026-07-05']
The stop value is exclusive, so use the next month to include all days of your target month.
Automatic Leap Year Handling
NumPy correctly handles February in leap and non-leap years:
import numpy as np
# February 2026 (leap year)
feb_2026 = np.arange('2026-02', '2026-03', dtype='datetime64[D]')
print(f"Feb 2026: {len(feb_2026)} days") # 29 days
# February 2023 (non-leap year)
feb_2023 = np.arange('2023-02', '2023-03', dtype='datetime64[D]')
print(f"Feb 2023: {len(feb_2023)} days") # 28 days
# Verify the last day
print(f"Last day 2026: {feb_2026[-1]}") # 2026-02-29
print(f"Last day 2023: {feb_2023[-1]}") # 2023-02-28
Output:
Feb 2026: 28 days
Feb 2023: 28 days
Last day 2026: 2026-02-28
Last day 2023: 2023-02-28
Different Time Resolutions
The datetime64 type supports various time units:
import numpy as np
# Daily resolution [D]
days = np.arange('2026-07', '2026-08', dtype='datetime64[D]')
print(f"Days in July: {len(days)}") # 31
# Monthly resolution [M]
months = np.arange('2026-01', '2025-01', dtype='datetime64[M]')
print(f"Months in 2026: {len(months)}") # 12
print(months[:3]) # ['2026-01' '2026-02' '2026-03']
# Yearly resolution [Y]
years = np.arange('2020', '2025', dtype='datetime64[Y]')
print(f"Years: {years}") # ['2020' '2021' '2022' '2023' '2026']
# Hourly resolution [h]
hours = np.arange('2026-07-01', '2026-07-02', dtype='datetime64[h]')
print(f"Hours in a day: {len(hours)}") # 24
Output:
Days in July: 31
Months in 2026: 0
[]
Years: ['2020' '2021' '2022' '2023' '2024']
Hours in a day: 24
Time Unit Reference
| Unit | Code | Example |
|---|---|---|
| Year | [Y] | 'datetime64[Y]' |
| Month | [M] | 'datetime64[M]' |
| Week | [W] | 'datetime64[W]' |
| Day | [D] | 'datetime64[D]' |
| Hour | [h] | 'datetime64[h]' |
| Minute | [m] | 'datetime64[m]' |
| Second | [s] | 'datetime64[s]' |
Date Arithmetic
Perform vectorized operations on date arrays:
import numpy as np
dates = np.arange('2026-01', '2026-02', dtype='datetime64[D]')
# Add days to each date
next_week = dates + 7
print(f"Jan 1 + 7: {next_week[0]}") # 2026-01-08
# Subtract days
last_week = dates - 7
print(f"Jan 1 - 7: {last_week[0]}") # 2023-12-25
# Difference between dates
diff = np.datetime64('2026-01-15') - np.datetime64('2026-01-01')
print(f"Difference: {diff}") # 14 days
Output:
Jan 1 + 7: 2026-01-08
Jan 1 - 7: 2025-12-25
Difference: 14 days
Adding Months and Years
import numpy as np
# Note: Adding months requires month units
months = np.arange('2026-01', '2026-04', dtype='datetime64[M]')
# Add 6 months
future = months + 6
print(future) # ['2026-07' '2026-08' '2026-09']
# Convert back to days for the first day of each month
first_days = future.astype('datetime64[D]')
print(first_days) # ['2026-07-01' '2026-08-01' '2026-09-01']
Output:
['2026-07' '2026-08' '2026-09']
['2026-07-01' '2026-08-01' '2026-09-01']
Reusable Function
Create a function to generate dates for any month:
import numpy as np
def get_month_dates(year, month):
"""Generate all dates for a given month."""
start = f'{year}-{month:02d}'
# Calculate next month
if month == 12:
end = f'{year + 1}-01'
else:
end = f'{year}-{month + 1:02d}'
return np.arange(start, end, dtype='datetime64[D]')
# Usage
july_2026 = get_month_dates(2026, 7)
print(f"July 2026: {len(july_2026)} days")
dec_2026 = get_month_dates(2026, 12)
print(f"December 2026: {len(dec_2026)} days")
feb_2026 = get_month_dates(2026, 2)
print(f"February 2026: {len(feb_2026)} days") # 29 (leap year)
Output:
July 2026: 31 days
December 2026: 31 days
February 2026: 28 days
Filtering Dates
Filter date arrays based on conditions:
import numpy as np
dates = np.arange('2026-07', '2026-08', dtype='datetime64[D]')
# Get weekday numbers (0=Monday, 6=Sunday)
# Convert to Python datetime for weekday calculation
import datetime
weekdays = np.array([
datetime.datetime.strptime(str(d), '%Y-%m-%d').weekday()
for d in dates
])
# Filter for weekdays only (Mon-Fri)
business_days = dates[weekdays < 5]
print(f"Business days in July: {len(business_days)}")
# Filter for weekends
weekends = dates[weekdays >= 5]
print(f"Weekend days in July: {len(weekends)}")
Output:
Business days in July: 23
Weekend days in July: 8
Using NumPy's busday Functions
import numpy as np
# Count business days in a month
start = np.datetime64('2026-07-01')
end = np.datetime64('2026-08-01')
business_days = np.busday_count(start, end)
print(f"Business days in July 2026: {business_days}") # 23
# Generate only business days
all_days = np.arange('2026-07', '2026-08', dtype='datetime64[D]')
is_business = np.is_busday(all_days)
business_only = all_days[is_business]
print(f"First 5 business days: {business_only[:5]}")
Output:
Business days in July 2026: 23
First 5 business days: ['2026-07-01' '2026-07-02' '2026-07-03' '2026-07-06' '2026-07-07']
Converting to Other Formats
import numpy as np
import datetime
dates = np.arange('2026-07', '2026-08', dtype='datetime64[D]')
# To Python datetime objects
py_dates = dates.astype('datetime64[D]').astype(datetime.datetime)
print(type(py_dates[0])) # <class 'datetime.datetime'>
# To string array
str_dates = dates.astype(str)
print(str_dates[:3]) # ['2026-07-01' '2026-07-02' '2026-07-03']
# To pandas DatetimeIndex (if using pandas)
import pandas as pd
pd_dates = pd.to_datetime(dates)
print(type(pd_dates)) # <class 'pandas.core.indexes.datetimes.DatetimeIndex'>
Output:
<class 'datetime.date'>
['2026-07-01' '2026-07-02' '2026-07-03']
<class 'pandas.core.indexes.datetimes.DatetimeIndex'>
Generating Date Ranges Across Multiple Months
import numpy as np
# Q3 2026 (July - September)
q3_dates = np.arange('2026-07', '2026-10', dtype='datetime64[D]')
print(f"Q3 2026: {len(q3_dates)} days") # 92 days
# Full year
year_dates = np.arange('2026-01', '2025-01', dtype='datetime64[D]')
print(f"2026: {len(year_dates)} days") # 366 days (leap year)
# Specific date range
range_dates = np.arange('2026-07-15', '2026-08-15', dtype='datetime64[D]')
print(f"Jul 15 - Aug 14: {len(range_dates)} days") # 31 days
Output:
Q3 2026: 92 days
2026: 0 days
Jul 15 - Aug 14: 31 days
Summary
| Component | Example | Description |
|---|---|---|
| Start | '2026-07' | First month (inclusive) |
| Stop | '2026-08' | Next month (exclusive) |
| dtype | 'datetime64[D]' | Daily resolution |
| Leap years | Automatic | Handled correctly |
| Arithmetic | dates + 7 | Add/subtract days |
Use np.arange('YYYY-MM', 'YYYY-MM+1', dtype='datetime64[D]') to generate all dates in a month with automatic handling of varying month lengths and leap years. This approach is memory-efficient and integrates seamlessly with NumPy's vectorized operations.