How to extract years from NumPy datetime64 arrays in Python using UliEngineering

You can easily extract the year component from NumPy datetime64 arrays using the UliEngineering Python library:

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

# Create a datetime64 array
dates = np.array(['2024-01-15', '2023-06-20', '2025-12-31'], dtype='datetime64[D]')

# Extract years
years = extract_years(dates)

print(f"Dates: {dates}")
print(f"Years: {years}")

Example output

extract_years_output.txt
Dates: ['2024-01-15' '2023-06-20' '2025-12-31']
Years: [2024 2023 2025]

The extract_years() function returns a NumPy array containing the year number for each datetime64 value in the input array.


Check out similar posts by category: Python, NumPy