
- 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 - Representing Dates and Times
Representing Dates and Times in NumPy
Representing dates and times in NumPy involves using specific data types to work with temporal data. The datetime64 data type is used for handling dates and times, while timedelta64 data type is used for representing time durations.
Temporal data refers to information that is related to time, such as dates, times, or time intervals. It helps track changes or events that occur over specific periods.
These types allow you to store, manipulate, and perform calculations with dates and times in a precise manner. For example, you can create arrays of dates, perform arithmetic operations like adding or subtracting days, and compare different dates easily.
The numpy.datetime64 Data Type
The numpy.datetime64 data type in NumPy is used to represent dates and times. It can handle different time units, from years to tiny fractions of a second, making it very flexible and precise for working with date and time data.
Example: Creating datetime64 Objects
In the following example, we are creating datetime64 objects with different units of time −
import numpy as np # Create datetime64 objects with different time units date_year = np.datetime64('2024', 'Y') date_month = np.datetime64('2024-11', 'M') date_day = np.datetime64('2024-11-26', 'D') date_hour = np.datetime64('2024-11-26T15', 'h') date_minute = np.datetime64('2024-11-26T15:45', 'm') date_second = np.datetime64('2024-11-26T15:45:30', 's') print(date_year) print(date_month) print(date_day) print(date_hour) print(date_minute) print(date_second)
Following is the output obtained −
2024 2024-11 2024-11-26 2024-11-26T15 2024-11-26T15:45 2024-11-26T15:45:30
Creating Arrays of datetime64
You can create arrays of datetime64 objects using the numpy.array() function. This is helpful for storing and working with multiple dates and times at once. Using arrays makes it easy and fast to perform operations on date and time data.
Example
In this example, we are creating an array of datetime64 objects representing different dates −
import numpy as np # Create an array of datetime64 objects dates = np.array(['2024-01-01', '2024-06-01', '2024-12-01'], dtype='datetime64[D]') print(dates)
This will produce the following result −
['2024-01-01' '2024-06-01' '2024-12-01']
The numpy.timedelta64 Data Type
The numpy.timedelta64 data type in NumPy is used to represent durations of time. It can handle different time units, letting you specify the accurate time intervals. The timedelta64 type makes it easy to perform precise calculations with time durations.
Example: Creating timedelta64 Objects
In the following example, we are creating timedelta64 objects representing different time intervals −
import numpy as np # Create timedelta64 objects with different time units delta_days = np.timedelta64(10, 'D') delta_hours = np.timedelta64(5, 'h') delta_minutes = np.timedelta64(30, 'm') print(delta_days) print(delta_hours) print(delta_minutes)
Following is the output of the above code −
10 days 5 hours 30 minutes
Arithmetic with datetime64 and timedelta64
NumPy supports arithmetic operations with datetime64 and timedelta64 objects, making it easy to calculate new dates and time durations. You can add or subtract time from a date or find the difference between two dates. These operations help you to manipulate dates and times quickly and efficiently.
For example, you can add or subtract days from a date or find the difference between two dates.
Example: Performing Date Arithmetic
In this example, we are adding and subtracting timedelta64 objects from datetime64 objects −
import numpy as np # Date arithmetic with datetime64 and timedelta64 start_date = np.datetime64('2024-01-01') end_date = start_date + np.timedelta64(45, 'D') duration = end_date - start_date print(end_date) print(duration)
The output obtained is as shown below −
2024-02-15 45 days
Comparing datetime64 Objects
NumPy allows you to compare datetime64 objects using several comparison operators, making it easier to analyze dates and times.
You can use operators like == to check if two dates are the same, != to check if they are different, < to see if one date is before another, and <= to see if one date is before or the same as another.
Similarly, you can use > to check if one date is after another and >= to check if one date is after or the same as another. These comparisons are important for working with time-based data.
Example
In this example, we are comparing two datetime64 objects to determine their temporal relationship −
import numpy as np # Comparing datetime64 objects date1 = np.datetime64('2024-01-01') date2 = np.datetime64('2024-12-31') is_earlier = date1 < date2 is_later = date1 > date2 print(is_earlier) print(is_later)
After executing the above code, we get the following output −
True False
Handling Time Zones
NumPy's datetime64 does not support time zones directly, but you can use external libraries like pytz or datetime to work with time zone-aware data.
Example: Working with Time Zones
In this example, we are using the pytz library to handle time zone conversions −
from datetime import datetime import pytz # Define time zones tz_utc = pytz.utc tz_est = pytz.timezone('US/Eastern') # Create datetime object and convert time zone dt_utc = datetime(2024, 1, 1, 12, 0, 0, tzinfo=tz_utc) dt_est = dt_utc.astimezone(tz_est) print("UTC:", dt_utc) print("EST:", dt_est)
The result produced is as follows −
UTC: 2024-01-01 12:00:00+00:00 EST: 2024-01-01 07:00:00-05:00