Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

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
Advertisements