How to generate datetime array for months in Python using UliEngineering

You can easily generate a NumPy datetime64 array for a range of months using the UliEngineering Python library:

generate_months.py
import numpy as np
from UliEngineering.Utils.Date import *

# Generate datetime array for January-June 2024
months = generate_months("2024-01-01", "2024-06-30")
print(f"Months Jan-Jun 2024: {len(months)}")
print(f"First month: {months[0]}")
print(f"Last month: {months[-1]}")

# Generate datetime array for a full year
months = generate_months("2024-01-01", "2024-12-31")
print(f"\nMonths in a year: {months}")

Example output

generate_months_output.txt
Months Jan-Jun 2024: 6
First month: 2024-01-01
Last month: 2024-06-01

Months in a year: ['2024-01-01' '2024-02-01' '2024-03-01' '2024-04-01' '2024-05-01'
 '2024-06-01' '2024-07-01' '2024-08-01' '2024-09-01' '2024-10-01' '2024-11-01'
 '2024-12-01']

The generate_months() function returns a NumPy datetime64 array containing the first day of each month from the start date (inclusive) to the end date (inclusive).


Check out similar posts by category: Python, NumPy