NumPy datetime64 and timedelta64
NumPy provides powerful support for handling date and time data using the datetime64 and timedelta64 data types. These types allow for efficient vectorized operations on dates, times, and durations, which is especially useful in time-series analysis and scientific computing.
Why Use datetime64 and timedelta64?
- Vectorized operations: Perform date arithmetic and comparisons across entire arrays.
- Precision control: Choose from time units ranging from years to nanoseconds (e.g., 'Y', 'M', 'D', 'h', 'm', 's', 'ms', etc.).
- Integration: Works seamlessly with NumPy's indexing, slicing, and broadcasting.
- Efficiency: Much faster and memory-efficient than using Python's native datetime module in large arrays.
Mastering datetime64 and timedelta64 will enable you to work with time-stamped data in a more efficient and expressive way.
Basic Usage of numpy.datetime64
The numpy.datetime64 object is used to represent dates and times in a vectorized way. You can create a single date, an array of dates, or specify the precision level such as day, hour, or minute.
Creating a Single datetime64 Object
import numpy as np
# Default precision is 'D' (day)
date = np.datetime64('2025-07-19')
print("Date:", date)
print("Type:", type(date))
import numpy as np
# Default precision is 'D' (day)
date = np.datetime64('2025-07-19')
print("Date:", date)
print("Type:", type(date))
Output
Date: 2025-07-19
Type: <class 'numpy.datetime64'>
Date: 2025-07-19
Type: <class 'numpy.datetime64'>
Creating an Array of Dates
# Create a range of dates
dates = np.array(['2025-01-01', '2025-01-02', '2025-01-03'], dtype='datetime64')
print(dates)
# Create a range of dates
dates = np.array(['2025-01-01', '2025-01-02', '2025-01-03'], dtype='datetime64')
print(dates)
Output
['2025-01-01' '2025-01-02' '2025-01-03']
['2025-01-01' '2025-01-02' '2025-01-03']
Specifying Time Precision
You can control the level of precision by passing a unit such as 'D' (day), 'h' (hour), 'm' (minute), 's' (second), etc.
dt_day = np.datetime64('2025-07-19', 'D')
dt_minute = np.datetime64('2025-07-19T13:45', 'm')
print("Day precision:", dt_day)
print("Minute precision:", dt_minute)
dt_day = np.datetime64('2025-07-19', 'D')
dt_minute = np.datetime64('2025-07-19T13:45', 'm')
print("Day precision:", dt_day)
print("Minute precision:", dt_minute)
Output
Day precision: 2025-07-19
Minute precision: 2025-07-19T13:45
Day precision: 2025-07-19
Minute precision: 2025-07-19T13:45
💡 Tip: Use higher precision (like 'm' or 's') when working with timestamps or time series data.
Basic Usage of numpy.timedelta64
The numpy.timedelta64 object is used to represent time durations or differences between two dates. It can be used directly to create a time span, or as the result of subtracting two datetime64 values.
Calculating the Difference Between Two Dates
When you subtract one datetime64 value from another, NumPy returns a timedelta64 object representing the duration between them.
import numpy as np
start = np.datetime64('2025-07-01')
end = np.datetime64('2025-07-10')
duration = end - start # This will be a timedelta64 object
print("Duration:", duration)
print("Type:", type(duration))
import numpy as np
start = np.datetime64('2025-07-01')
end = np.datetime64('2025-07-10')
duration = end - start # This will be a timedelta64 object
print("Duration:", duration)
print("Type:", type(duration))
Output
Duration: 9 days
Type: <class 'numpy.timedelta64'>
Duration: 9 days
Type: <class 'numpy.timedelta64'>
The result 9 days is a timedelta64 object, meaning there are 9 full calendar days between July 1 and July 10. This type of object can be added to or subtracted from datetime64 values to shift dates forward or backward in time.
💡 Tip: You can also create timedelta64 values directly with custom time units like days ('D'), hours ('h'), or minutes ('m').
Creating timedelta64 Objects
You can create numpy.timedelta64 objects to represent fixed durations of time, such as days, hours, or minutes. These durations are useful when performing date arithmetic with datetime64 values or storing time differences.
Specifying Time Units
When creating a timedelta64, you pass two arguments:
- The numeric duration
- A string representing the unit (e.g. 'D' for days, 'h' for hours)
import numpy as np
delta_days = np.timedelta64(5, 'D') # 5 days
delta_hours = np.timedelta64(12, 'h') # 12 hours
delta_minutes = np.timedelta64(30, 'm') # 30 minutes
delta_seconds = np.timedelta64(45, 's') # 45 seconds
print("Days:", delta_days)
print("Hours:", delta_hours)
print("Minutes:", delta_minutes)
print("Seconds:", delta_seconds)
import numpy as np
delta_days = np.timedelta64(5, 'D') # 5 days
delta_hours = np.timedelta64(12, 'h') # 12 hours
delta_minutes = np.timedelta64(30, 'm') # 30 minutes
delta_seconds = np.timedelta64(45, 's') # 45 seconds
print("Days:", delta_days)
print("Hours:", delta_hours)
print("Minutes:", delta_minutes)
print("Seconds:", delta_seconds)
Output
Days: 5 days
Hours: 12 hours
Minutes: 30 minutes
Seconds: 45 seconds
Days: 5 days
Hours: 12 hours
Minutes: 30 minutes
Seconds: 45 seconds
Available Time Units
NumPy supports a wide range of time units when creating timedelta64 objects:
- 'Y' – years
- 'M' – months
- 'W' – weeks
- 'D' – days
- 'h' – hours
- 'm' – minutes
- 's' – seconds
- 'ms' – milliseconds
- 'us' – microseconds
- 'ns' – nanoseconds
💡 Tip: Make sure the unit you choose matches your use case. For example, use 'h' for hourly intervals in time series data.
Arithmetic with datetime64
NumPy allows you to perform arithmetic operations with datetime64 and timedelta64 objects. This makes it easy to add or subtract time durations from dates and calculate differences between dates.
Adding and Subtracting Time Durations
You can add or subtract a timedelta64 duration to/from a datetime64 object to shift the date forward or backward in time.
import numpy as np
date = np.datetime64('2025-07-19')
print("Original date:", date)
# Add 5 days
date_plus_5 = date + np.timedelta64(5, 'D')
print("Date plus 5 days:", date_plus_5)
# Subtract 3 days
date_minus_3 = date - np.timedelta64(3, 'D')
print("Date minus 3 days:", date_minus_3)
import numpy as np
date = np.datetime64('2025-07-19')
print("Original date:", date)
# Add 5 days
date_plus_5 = date + np.timedelta64(5, 'D')
print("Date plus 5 days:", date_plus_5)
# Subtract 3 days
date_minus_3 = date - np.timedelta64(3, 'D')
print("Date minus 3 days:", date_minus_3)
Output
Original date: 2025-07-19
Date plus 5 days: 2025-07-24
Date minus 3 days: 2025-07-16
Original date: 2025-07-19
Date plus 5 days: 2025-07-24
Date minus 3 days: 2025-07-16
Subtracting Two datetime64 Values
Subtracting one datetime64 from another returns a timedelta64 object representing the duration between the two dates.
import numpy as np
start = np.datetime64('2025-07-01')
end = np.datetime64('2025-07-10')
duration = end - start
print("Duration between dates:", duration)
print("Type:", type(duration))
import numpy as np
start = np.datetime64('2025-07-01')
end = np.datetime64('2025-07-10')
duration = end - start
print("Duration between dates:", duration)
print("Type:", type(duration))
Output
Duration between dates: 9 days
Type: <class 'numpy.timedelta64'>
Duration between dates: 9 days
Type: <class 'numpy.timedelta64'>
💡 Tip: You can use this to calculate elapsed time or intervals between events in your data.
Comparisons and Filtering with datetime64
You can compare datetime64 objects using standard comparison operators like >, <, ==, and others. This allows you to filter arrays of dates based on conditions.
Comparing Individual Dates
import numpy as np
date1 = np.datetime64('2025-07-19')
date2 = np.datetime64('2025-07-25')
print("Is date1 earlier than date2?", date1 < date2)
print("Is date1 equal to date2?", date1 == date2)
import numpy as np
date1 = np.datetime64('2025-07-19')
date2 = np.datetime64('2025-07-25')
print("Is date1 earlier than date2?", date1 < date2)
print("Is date1 equal to date2?", date1 == date2)
Output
Is date1 earlier than date2? True
Is date1 equal to date2? False
Is date1 earlier than date2? True
Is date1 equal to date2? False
Filtering Arrays of Dates
You can use comparison operators on arrays of datetime64 to create boolean masks, which help filter or select dates matching your criteria.
import numpy as np
dates = np.array(['2025-07-15', '2025-07-19', '2025-07-23', '2025-07-28'], dtype='datetime64')
# Select dates after July 20, 2025
mask = dates > np.datetime64('2025-07-20')
filtered_dates = dates[mask]
print("Original dates:", dates)
print("Dates after 2025-07-20:", filtered_dates)
import numpy as np
dates = np.array(['2025-07-15', '2025-07-19', '2025-07-23', '2025-07-28'], dtype='datetime64')
# Select dates after July 20, 2025
mask = dates > np.datetime64('2025-07-20')
filtered_dates = dates[mask]
print("Original dates:", dates)
print("Dates after 2025-07-20:", filtered_dates)
Output
Original dates: ['2025-07-15' '2025-07-19' '2025-07-23' '2025-07-28']
Dates after 2025-07-20: ['2025-07-23' '2025-07-28']
Original dates: ['2025-07-15' '2025-07-19' '2025-07-23' '2025-07-28']
Dates after 2025-07-20: ['2025-07-23' '2025-07-28']
💡 Tip: Boolean masks are powerful for selecting date ranges or filtering time series data based on conditions.
Frequently Asked Questions
What is datetime64 in NumPy?
What is datetime64 in NumPy?
datetime64 is a NumPy type for handling dates and times with high precision. It is used to create arrays of dates and times for applications like time series analysis, simulations, and scientific computations.
How do I create a datetime64 object in NumPy?
How do I create a datetime64 object in NumPy?
You can create a datetime64 object using np.datetime64(). For example: np.datetime64('2025-07-20') creates a datetime64 object for July 20, 2025.
What is timedelta64 in NumPy?
What is timedelta64 in NumPy?
timedelta64 represents the difference between two datetime64 objects, allowing for operations like addition, subtraction, and more.
How do I subtract two datetime64 objects?
How do I subtract two datetime64 objects?
You can subtract two datetime64 objects to get a timedelta64 object. For example: np.datetime64('2025-07-20') - np.datetime64('2025-07-19') gives a timedelta64 object with a 1-day difference.
Can I add a timedelta64 object to a datetime64 object?
Can I add a timedelta64 object to a datetime64 object?
Yes, you can add a timedelta64 object to a datetime64 object. For example: np.datetime64('2025-07-20') + np.timedelta64(1, 'D') results in 2025-07-21.
What units can timedelta64 represent?
What units can timedelta64 represent?
timedelta64 can represent time differences in units like 'Y' for years, 'M' for months, 'D' for days, 'h' for hours, 'm' for minutes, and 's' for seconds.
How do I convert datetime64 to a different unit?
How do I convert datetime64 to a different unit?
You can convert datetime64 to a different unit using astype(). For example: np.datetime64('2025-07-20').astype('datetime64[s]') converts the date to seconds.
How do I get the current date and time using datetime64?
How do I get the current date and time using datetime64?
Use np.datetime64('now') to get the current date and time as a datetime64 object.
What's Next?
Next, we'll dive into Saving and Loading `.npy` Files in NumPy. You'll discover how to efficiently store your NumPy arrays to disk and quickly load them back into memory for later use. Whether you're working with large datasets or need to persist data between sessions, this tutorial will walk you through the essentials of saving and loading `.npy` files.