
- 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 - Basics of Dates and Times
Dates and Times in NumPy
Dates and times in NumPy refer to handling and manipulating date and time data within arrays. NumPy provides the datetime64 and timedelta64 data types for working with dates and times.
These types allow you to perform operations like addition, subtraction, and comparison of dates and times, as well as converting between different time units (e.g., days, hours, minutes).
The NumPy datetime64 Data Type
The numpy.datetime64 data type is used to represent dates and times. It provides various units of time such as years, months, days, hours, minutes, and seconds. This data type allows for precise representation and manipulation of date and time data.
The datetime64 data type allows for flexible representation of dates and times with varying levels of precision.
Example: Creating datetime64 Objects
In the following example, we are creating datetime64 objects using different units of time −
import numpy as np # Create datetime64 objects date1 = np.datetime64('2023-01-01') date2 = np.datetime64('2023-01-01 12:30') date3 = np.datetime64('2023-01-01 12:30:45') print(date1) print(date2) print(date3)
Following is the output obtained −
2023-01-01 2023-01-01T12:30 2023-01-01T12:30:45
Creating Arrays of datetime64
You can create arrays of datetime64 objects using the numpy.array() function. This allows for storage and manipulation of multiple date and time values.
Arrays of datetime64 objects are useful for performing vectorized operations on date and time data.
Example: Creating Arrays of datetime64
In this example, we are creating an array of datetime64 objects in NumPy −
import numpy as np # Create an array of datetime64 objects dates = np.array(['2023-01-01', '2023-02-01', '2023-03-01'], dtype='datetime64') print(dates)
This will produce the following result −
['2023-01-01' '2023-02-01' '2023-03-01']
Date Arithmetic with datetime64
NumPy allows for easy arithmetic operations with datetime64 objects, including addition and subtraction of time units.
You can add or subtract time units such as days, months, or years to manipulate date and time values.
Example: Adding and Subtracting Time Units
In the following example, we are performing arithmetic operations on datetime64 objects −
import numpy as np import datetime # Define the initial date date = np.datetime64('2023-01-01') # Add 10 days to the initial date date_plus_10_days = date + np.timedelta64(10, 'D') # Subtract 1 month from the initial date by converting to datetime and using a timedelta date_as_datetime = date.astype(datetime.datetime) # Approximate a month as 30 days date_minus_1_month = date_as_datetime - datetime.timedelta(days=30) print(date_plus_10_days) print(np.datetime64(date_minus_1_month))
Following is the output of the above code −
2023-01-11 2022-12-02
Comparing datetime64 Objects
In NumPy, you can use comparison operators with datetime64 objects to easily compare dates and times. These operators allow you to check whether one date is earlier, later, or the same as another date.
Following are the comparison operators for datetime64 data type −
- Equality (==): Checks if two dates are exactly the same.
- Inequality (!=): Checks if two dates are different.
- Less than (<): Checks if the first date is earlier than the second date.
- Less than or equal to (<=): Checks if the first date is earlier than or exactly the same as the second date.
- Greater than (>): Checks if the first date is later than the second date.
- Greater than or equal to (>=): Checks if the first date is later than or exactly the same as the second date.
Example: Comparing Dates
In this example, we are comparing datetime64 objects using the less than and greater than comparison operators −
import numpy as np # Comparing datetime64 objects date1 = np.datetime64('2023-01-01') date2 = np.datetime64('2023-02-01') is_earlier = date1 < date2 is_later = date1 > date2 print(is_earlier) print(is_later)
The output obtained is as shown below −
True False
Converting between datetime64 and timedelta64
NumPy allows you to convert between 'datetime64' and 'timedelta64' objects. This makes it easy to calculate time intervals and durations. For example, you can add or subtract days, months, or years from a specific date or find out the difference between two dates.
Example: Conversion between datetime64 and timedelta64
In this example, we are converting datetime64 objects to timedelta64 objects and vice versa −
import numpy as np # Converting datetime64 to timedelta64 start_date = np.datetime64('2023-01-01') end_date = np.datetime64('2023-02-01') duration = end_date - start_date print(duration) # Converting timedelta64 to datetime64 new_date = start_date + duration print(new_date)
After executing the above code, we get the following output −
31 days 2023-02-01
Working with Time Units
NumPy supports various time units for datetime64 and timedelta64, including years, months, weeks, days, hours, minutes, and seconds. Using appropriate time units ensures accurate representation and manipulation of date and time data.
Example: Using Different Time Units
In this example, we are demonstrating the use of different time units with datetime64 and timedelta64 objects −
import numpy as np # Using different time units date_year = np.datetime64('2023', 'Y') date_month = np.datetime64('2023-01', 'M') date_week = np.datetime64('2023-01-01', 'W') print(date_year) print(date_month) print(date_week)
We get the output as shown below −
2023 2023-01 2022-12-29