
- NumPy - Home
- NumPy - Introduction
- NumPy - Environment
- NumPy Arrays
- NumPy - Ndarray Object
- NumPy - Data Types
- NumPy Creating and Manipulating Arrays
- NumPy - Array Creation Routines
- NumPy - Array Manipulation
- NumPy - Array from Existing Data
- NumPy - Array From Numerical Ranges
- NumPy - Iterating Over Array
- NumPy - Reshaping Arrays
- NumPy - Concatenating Arrays
- NumPy - Stacking Arrays
- NumPy - Splitting Arrays
- NumPy - Flattening Arrays
- NumPy - Transposing Arrays
- NumPy Indexing & Slicing
- NumPy - Indexing & Slicing
- NumPy - Indexing
- NumPy - Slicing
- NumPy - Advanced Indexing
- NumPy - Fancy Indexing
- NumPy - Field Access
- NumPy - Slicing with Boolean Arrays
- NumPy Array Attributes & Operations
- NumPy - Array Attributes
- NumPy - Array Shape
- NumPy - Array Size
- NumPy - Array Strides
- NumPy - Array Itemsize
- NumPy - Broadcasting
- NumPy - Arithmetic Operations
- NumPy - Array Addition
- NumPy - Array Subtraction
- NumPy - Array Multiplication
- NumPy - Array Division
- NumPy Advanced Array Operations
- NumPy - Swapping Axes of Arrays
- NumPy - Byte Swapping
- NumPy - Copies & Views
- NumPy - Element-wise Array Comparisons
- NumPy - Filtering Arrays
- NumPy - Joining Arrays
- NumPy - Sort, Search & Counting Functions
- NumPy - Searching Arrays
- NumPy - Union of Arrays
- NumPy - Finding Unique Rows
- NumPy - Creating Datetime Arrays
- NumPy - Binary Operators
- NumPy - String Functions
- NumPy - Matrix Library
- NumPy - Linear Algebra
- NumPy - Matplotlib
- NumPy - Histogram Using Matplotlib
- NumPy Sorting and Advanced Manipulation
- NumPy - Sorting Arrays
- NumPy - Sorting along an axis
- NumPy - Sorting with Fancy Indexing
- NumPy - Structured Arrays
- NumPy - Creating Structured Arrays
- NumPy - Manipulating Structured Arrays
- NumPy - Record Arrays
- Numpy - Loading Arrays
- Numpy - Saving Arrays
- NumPy - Append Values to an Array
- NumPy - Swap Columns of Array
- NumPy - Insert Axes to an Array
- NumPy Handling Missing Data
- NumPy - Handling Missing Data
- NumPy - Identifying Missing Values
- NumPy - Removing Missing Data
- NumPy - Imputing Missing Data
- NumPy Performance Optimization
- NumPy - Performance Optimization with Arrays
- NumPy - Vectorization with Arrays
- NumPy - Memory Layout of Arrays
- Numpy Linear Algebra
- NumPy - Linear Algebra
- NumPy - Matrix Library
- NumPy - Matrix Addition
- NumPy - Matrix Subtraction
- NumPy - Matrix Multiplication
- NumPy - Element-wise Matrix Operations
- NumPy - Dot Product
- NumPy - Matrix Inversion
- NumPy - Determinant Calculation
- NumPy - Eigenvalues
- NumPy - Eigenvectors
- NumPy - Singular Value Decomposition
- NumPy - Solving Linear Equations
- NumPy - Matrix Norms
- NumPy Element-wise Matrix Operations
- NumPy - Sum
- NumPy - Mean
- NumPy - Median
- NumPy - Min
- NumPy - Max
- NumPy Set Operations
- NumPy - Unique Elements
- NumPy - Intersection
- NumPy - Union
- NumPy - Difference
- NumPy Random Number Generation
- NumPy - Random Generator
- NumPy - Permutations & Shuffling
- NumPy - Uniform distribution
- NumPy - Normal distribution
- NumPy - Binomial distribution
- NumPy - Poisson distribution
- NumPy - Exponential distribution
- NumPy - Rayleigh Distribution
- NumPy - Logistic Distribution
- NumPy - Pareto Distribution
- NumPy - Visualize Distributions With Sea born
- NumPy - Matplotlib
- NumPy - Multinomial Distribution
- NumPy - Chi Square Distribution
- NumPy - Zipf Distribution
- NumPy File Input & Output
- NumPy - I/O with NumPy
- NumPy - Reading Data from Files
- NumPy - Writing Data to Files
- NumPy - File Formats Supported
- NumPy Mathematical Functions
- NumPy - Mathematical Functions
- NumPy - Trigonometric functions
- NumPy - Exponential Functions
- NumPy - Logarithmic Functions
- NumPy - Hyperbolic functions
- NumPy - Rounding functions
- NumPy Fourier Transforms
- NumPy - Discrete Fourier Transform (DFT)
- NumPy - Fast Fourier Transform (FFT)
- NumPy - Inverse Fourier Transform
- NumPy - Fourier Series and Transforms
- NumPy - Signal Processing Applications
- NumPy - Convolution
- NumPy Polynomials
- NumPy - Polynomial Representation
- NumPy - Polynomial Operations
- NumPy - Finding Roots of Polynomials
- NumPy - Evaluating Polynomials
- NumPy Statistics
- NumPy - Statistical Functions
- NumPy - Descriptive Statistics
- NumPy Datetime
- NumPy - Basics of Date and Time
- NumPy - Representing Date & Time
- NumPy - Date & Time Arithmetic
- NumPy - Indexing with Datetime
- NumPy - Time Zone Handling
- NumPy - Time Series Analysis
- NumPy - Working with Time Deltas
- NumPy - Handling Leap Seconds
- NumPy - Vectorized Operations with Datetimes
- NumPy ufunc
- NumPy - ufunc Introduction
- NumPy - Creating Universal Functions (ufunc)
- NumPy - Arithmetic Universal Function (ufunc)
- NumPy - Rounding Decimal ufunc
- NumPy - Logarithmic Universal Function (ufunc)
- NumPy - Summation Universal Function (ufunc)
- NumPy - Product Universal Function (ufunc)
- NumPy - Difference Universal Function (ufunc)
- NumPy - Finding LCM with ufunc
- NumPy - ufunc Finding GCD
- NumPy - ufunc Trigonometric
- NumPy - Hyperbolic ufunc
- NumPy - Set Operations ufunc
- NumPy Useful Resources
- NumPy - Quick Guide
- NumPy - Cheatsheet
- NumPy - Useful Resources
- NumPy - Discussion
- NumPy Compiler
NumPy - Date and Time Arithmetic
Date and Time Arithmetic in NumPy
Date and time arithmetic in NumPy refers to performing operations like adding or subtracting time from dates, or calculating the difference between two dates.
NumPy provides the datetime64 and timedelta64 data types to perform these operations. For example, you can add days to a specific date or find how many days are between two dates.
This makes it easy to manipulate time-related data for tasks such as scheduling, time series analysis, and event tracking.
Adding and Subtracting Dates and Times
NumPy allows for the addition and subtraction of timedelta64 objects to and from datetime64 objects. This makes it easy to calculate new dates and times based on specific intervals.
Example: Adding Time Intervals
In the following example, we are adding various timedelta64 intervals to a datetime64 object −
import numpy as np # Define a base date base_date = np.datetime64('2024-01-01') # Add different time intervals date_plus_10_days = base_date + np.timedelta64(10, 'D') # Add months manually by changing to a monthly precision date_plus_2_months = np.datetime64(base_date, 'M') + np.timedelta64(2, 'M') # Add years manually by changing to a yearly precision date_plus_5_years = np.datetime64(base_date, 'Y') + np.timedelta64(5, 'Y') print(date_plus_10_days) print(date_plus_2_months) print(date_plus_5_years)
We get the output as shown below −
2024-01-11 2024-03 2029
Example: Subtracting Time Intervals
In this example, we are subtracting various timedelta64 intervals from a datetime64 object −
import numpy as np # Define a base date base_date = np.datetime64('2024-01-01') # Subtract different time intervals date_minus_10_days = base_date - np.timedelta64(10, 'D') # Subtract months manually by changing to monthly precision date_minus_2_months = np.datetime64(base_date, 'M') - np.timedelta64(2, 'M') # Subtract years manually by changing to yearly precision date_minus_5_years = np.datetime64(base_date, 'Y') - np.timedelta64(5, 'Y') print(date_minus_10_days) print(date_minus_2_months) print(date_minus_5_years)
Following is the output obtained −
2023-12-22 2023-11 2019
Calculating Differences Between Dates
NumPy allows you to calculate the differences between two datetime64 objects, resulting in timedelta64 objects. This is useful for determining the duration between two dates or times.
Example
In this example, we are calculating the difference between two datetime64 objects −
import numpy as np # Define two dates date1 = np.datetime64('2024-01-01') date2 = np.datetime64('2024-12-31') # Calculate the difference difference = date2 - date1 print(difference)
This will produce the following result −
365 days
Using Vectorized Operations
NumPy supports vectorized operations on arrays of datetime64 and timedelta64 objects, which means you can perform calculations on entire arrays of dates and times at once, without needing to loop through them one by one.
Vectorized operations allow you to apply the same operation across all elements in the array simultaneously, which is much quicker than processing each element individually.
Example: Vectorized Date Arithmetic
In this example, we are performing vectorized addition of timedelta64 intervals to an array of datetime64 objects −
import numpy as np # Define an array of dates dates = np.array(['2024-01-01', '2024-06-01', '2024-12-01'], dtype='datetime64[D]') # Add 10 days to each date new_dates = dates + np.timedelta64(10, 'D') print(new_dates)
Following is the output of the above code −
['2024-01-11' '2024-06-11' '2024-12-11']
Combine datetime64 and timedelta64 in Operations
NumPy allows you to combine datetime64 and timedelta64 objects in arithmetic operations, making it easy to perform complex date and time calculations.
You can add or subtract time durations to/from specific dates, or even calculate the difference between two dates. This capability allows for easy manipulation of dates and times, supporting various temporal operations like shifting dates by a specific interval or calculating time differences.
Example
In this example, we are performing multiple arithmetic operations combining datetime64 and timedelta64 objects −
import numpy as np # Define a base date base_date = np.datetime64('2024-01-01') # Perform complex date arithmetic # Add 5 years new_date = np.datetime64(base_date, 'Y') + np.timedelta64(5, 'Y') # Subtract 3 months new_date = np.datetime64(new_date, 'M') - np.timedelta64(3, 'M') # Add 15 days new_date = new_date + np.timedelta64(15, 'D') print(new_date)
The output obtained is as shown below −
2028-10-16