DatetimeIndex#

class DatetimeIndex#

Immutable ndarray-like of datetime64 data.

Example#

import pandasCore as pd

# Create DatetimeIndex
idx = pd.DatetimeIndex([1, 2, 3], name='my_index')
print(len(idx))  # 3

Attributes#

Attribute

Description

Example

day

The day of the datetime

day_of_week

The day of the week with Monday=0, Sunday=6

day_of_year

The ordinal day of the year

dayofweek

The day of the week with Monday=0, Sunday=6

dayofyear

The ordinal day of the year

dtype

Return the dtype object of the underlying data

empty

Indicator whether DatetimeIndex is empty

freq

Return the frequency object

has_duplicates

Return if the index has duplicate values

hour

The hours of the datetime

is_leap_year

Boolean indicator if the date belongs to a leap year

is_monotonic_decreasing

Return if the index is monotonic decreasing

is_monotonic_increasing

Return if the index is monotonic increasing

is_month_end

Indicator for whether the date is the last day of the month

is_month_start

Indicator for whether the date is the first day of the month

is_quarter_end

Indicator for whether the date is the last day of a quarter

is_quarter_start

Indicator for whether the date is the first day of a quarter

is_unique

Return if the index has unique values

is_year_end

Indicator for whether the date is the last day of the year

is_year_start

Indicator for whether the date is the first day of the year

microsecond

The microseconds of the datetime

minute

The minutes of the datetime

month

The month of the datetime

name

Return the name of the DatetimeIndex

nanosecond

The nanoseconds of the datetime

ndim

Number of dimensions of the underlying data

nlevels

Number of levels in this index

quarter

The quarter of the date

second

The seconds of the datetime

shape

Return a tuple of the shape of the underlying data

size

Return the number of elements in the DatetimeIndex

str

Vectorized string functions for Index.

View

tz

Return timezone, if any

weekday

The day of the week with Monday=0, Sunday=6

year

The year of the datetime

Construction#

Method

Description

Example

__init__() (*args, **kwargs) | () | (data: object = None, freq: object = None, tz: object = None, normalize: object = None, closed: object = None, ambiguous: str = 'raise', dayfirst: bool = False, yearfirst: bool = False, dtype: object = None, copy: bool = False, name: object = None)

Create an empty DatetimeIndex

View

Indexing / Selection#

Method

Description

Example

__getitem__() (arg0: object)

take() (indices: collections.abc.Sequence[typing.SupportsInt], axis: typing.SupportsInt = 0, allow_fill: bool = True, fill_value: object = None)

Return a new DatetimeIndex of the values selected by the indices.

where() (cond: collections.abc.Sequence[bool], other: object = None)

Replace values where the condition is False.

Data Manipulation#

Method

Description

Example

drop() (labels: collections.abc.Sequence[typing.SupportsInt], errors: str = 'raise')

Make new DatetimeIndex with passed list of labels deleted.

droplevel() (level: typing.SupportsInt = 0)

Return index with requested level(s) removed.

insert() (loc: typing.SupportsInt, item: typing.SupportsInt)

Insert new item at specified position

reindex() (target: pandasCore.DatetimeIndex, method: object = None, level: object = None, limit: object = None, tolerance: object = None)

Conform DatetimeIndex to new index.

rename() (name: object, *, inplace: bool = False)

Alter DatetimeIndex name.

set_names() (names: object, *, level: object = None, inplace: bool = False)

Set DatetimeIndex name.

Missing Data#

Method

Description

Example

dropna() (how: str = 'any')

Return DatetimeIndex without NA/NaT values.

fillna() (value: object = None, downcast: object = None)

Fill NA/NaT values with the specified value.

isna() ()

Detect missing values (NaT)

isnull() ()

Alias for isna

notna() ()

Detect existing (non-missing) values

notnull() ()

Alias for notna

Statistics#

Method

Description

Example

max() (axis: object = None, skipna: bool = True)

Return the maximum value of the Index.

mean() (*, skipna: bool = True, axis: object = 0)

Return the mean value of the Index as nanoseconds.

min() (axis: object = None, skipna: bool = True)

Return the minimum value of the Index.

nunique() (dropna: bool = True)

Return number of unique elements

std() (axis: object = None, dtype: object = None, out: object = None, ddof: typing.SupportsInt = 1, keepdims: bool = False, skipna: bool = True)

Return the standard deviation as nanoseconds.

value_counts() (normalize: bool = False, sort: bool = True, ascending: bool = False, bins: object = None, dropna: bool = True)

Return a Series containing counts of unique values.

Aggregation#

Method

Description

Example

groupby() (values: collections.abc.Sequence[typing.SupportsInt])

Group the index labels by a mapping

map() (mapper: collections.abc.Callable, na_action: object = None)

Map values using an input mapping or function.

Comparison#

Method

Description

Example

__eq__() (self, value, /)

Return self==value.

__ge__() (self, value, /)

Return self>=value.

__gt__() (self, value, /)

Return self>value.

__le__() (self, value, /)

Return self<=value.

__lt__() (self, value, /)

Return self<value.

__ne__() (self, value, /)

Return self!=value.

equals() (other: pandasCore.DatetimeIndex)

Determine if two DatetimeIndex objects are equal

Sorting#

Method

Description

Example

argsort() (*, ascending: bool = True, kind: str = 'quicksort', na_position: str = 'last')

Return the indices that would sort the index.

searchsorted() (value: typing.SupportsInt, side: str = 'left', sorter: object = None)

Find indices where elements should be inserted to maintain order.

sort_values() (*, return_indexer: bool = False, ascending: bool = True, na_position: str = 'last', key: object = None)

Return a sorted copy of the index.

Reshaping#

Method

Description

Example

to_frame() (index: bool = True, name: object = None)

Create a DataFrame with a column containing the Index.

transpose() ()

Return the transpose (identity for 1D)

Combining#

Method

Description

Example

append() (other: pandasCore.DatetimeIndex)

Append another DatetimeIndex to this one

join() (other: pandasCore.DatetimeIndex, *, how: str = 'left', level: object = None, return_indexers: bool = False, sort: bool = False)

Compute join of this index with other.

Time Series#

Method

Description

Example

asof() (label: typing.SupportsInt)

Return the label from the index, or NaT

diff() (periods: typing.SupportsInt = 1)

Compute differences between consecutive elements

shift() (periods: typing.SupportsInt = 1, freq: object = None)

Shift index by desired number of periods.

to_period() (*args, **kwargs)

Cast to PeriodArray/PeriodIndex at a particular frequency.

tz_convert() (tz: object)

Convert tz-aware DatetimeIndex from one timezone to another.

tz_localize() (tz: object, ambiguous: str = 'raise', nonexistent: str = 'raise')

Localize tz-naive DatetimeIndex to tz-aware DatetimeIndex.

I/O#

Method

Description

Example

to_flat_index() ()

Identity method; returns a copy

to_julian_date() ()

Convert DatetimeIndex to Julian Date.

to_list() ()

Return a list of the DatetimeIndex values as nanoseconds

to_numpy() (dtype: object = None, copy: bool = False, na_value: object = None)

Convert to a NumPy array.

to_pydatetime() (*args, **kwargs)

Return DatetimeIndex as object ndarray of datetime.datetime objects.

to_series() (index: object = None, name: object = None)

Create a Series with the Index values.

tolist() ()

Return a list of the DatetimeIndex values as nanoseconds

Conversion#

Method

Description

Example

astype() (dtype: str, copy: bool = True)

Cast to a specified dtype.

copy() (name: object = None, deep: bool = False)

Make a copy of this DatetimeIndex.

infer_objects() (copy: bool = True)

Attempt to infer better dtype for object columns.

view() (cls: object = None)

Return a view on the index values.

Iteration#

Method

Description

Example

__contains__() (arg0: typing.SupportsInt)

__iter__() ()

__len__() ()

Set Operations#

Method

Description

Example

difference() (other: pandasCore.DatetimeIndex, sort: object = None)

Return a new DatetimeIndex with elements not in other.

drop_duplicates() (*, keep: str = 'first')

Return DatetimeIndex with duplicate values removed.

duplicated() (keep: str = 'first')

Indicate duplicate index values

intersection() (other: pandasCore.DatetimeIndex, sort: bool = False)

Form the intersection of two DatetimeIndex objects.

isin() (values: collections.abc.Sequence[typing.SupportsInt], level: object = None)

Check if values are in the DatetimeIndex.

symmetric_difference() (other: pandasCore.DatetimeIndex, result_name: object = None, sort: object = None)

Compute the symmetric difference of two Index objects.

union() (other: pandasCore.DatetimeIndex, sort: object = None)

Form the union of two DatetimeIndex objects.

unique() (level: object = None)

Return unique values in the index.

Datetime Methods#

Method

Description

Example

ceil() (freq: str, ambiguous: str = 'raise', nonexistent: str = 'raise')

Perform ceil operation on the data to the specified freq.

floor() (freq: str, ambiguous: str = 'raise', nonexistent: str = 'raise')

Perform floor operation on the data to the specified freq.

normalize() ()

Convert times to midnight.

round() (freq: str, ambiguous: str = 'raise', nonexistent: str = 'raise')

Perform round operation on the data to the specified freq.

strftime() (date_format: str)

Convert to string array using specified date_format.

Other Methods#

Method

Description

Example

__hash__() (self, /)

Return hash(self).

__repr__() ()

__str__() ()

all() (*, axis: object = None, skipna: bool = True)

Return whether all elements are truthy (non-NaT).

any() (*, axis: object = None, skipna: bool = True)

Return whether any element is truthy (non-NaT).

argmax() (axis: object = None, skipna: bool = True)

Return int position of the largest value in the Index.

argmin() (axis: object = None, skipna: bool = True)

Return int position of the smallest value in the Index.

as_unit() (unit: str, round_ok: bool = True)

Convert to a new unit resolution.

asof_locs() (where: pandasCore.DatetimeIndex, mask: collections.abc.Sequence[bool] | None = None)

Return the locations (indices) for asof queries.

day_name() (locale: object = None)

Return the day names of the DatetimeIndex with specified locale.

delete() (loc: typing.SupportsInt)

Make new DatetimeIndex with element at position deleted

factorize() (sort: bool = False, use_na_sentinel: bool = True)

Encode the object as an enumerated type or categorical variable.

format() (name: bool = False, formatter: object = None, na_rep: str = 'NaT', date_format: object = None)

Render a string representation of the Index.

get_indexer() (target: pandasCore.DatetimeIndex, method: object = None, limit: object = None, tolerance: object = None)

Compute indexer and mask for new index given the current index.

get_indexer_for() (target: collections.abc.Sequence[typing.SupportsInt])

Get indexer for target values

get_indexer_non_unique() (target: pandasCore.DatetimeIndex)

Get indexer and missing indices for non-unique target

get_level_values() (level: typing.SupportsInt)

Return an Index of values for requested level

get_loc() (key: typing.SupportsInt)

Get integer location for requested label

get_slice_bound() (label: typing.SupportsInt, side: str)

Get slice bound

holds_integer() ()

Return if the index holds integer values

identical() (other: pandasCore.DatetimeIndex)

Determine if two DatetimeIndex objects are identical

indexer_at_time() (time: str, asof: bool = False)

Return index locations of values at particular time of day.

indexer_between_time() (start_time: str, end_time: str, include_start: bool = True, include_end: bool = True)

Return index locations of values between particular times of day.

isocalendar() ()

Return a DataFrame containing ISO year, week number, and weekday.

item() ()

Return the first element of the data as a scalar

memory_usage() (deep: bool = False)

Memory usage of the Index values

month_name() (locale: object = None)

Return the month names of the DatetimeIndex with specified locale.

putmask() (mask: collections.abc.Sequence[bool], value: typing.SupportsInt)

Return a new DatetimeIndex with values put where mask is True.

ravel() (order: str = 'C')

Return a flattened array of the index values.

repeat() (repeats: typing.SupportsInt, axis: object = None)

Repeat elements of a DatetimeIndex.

slice_indexer() (start: object = None, end: object = None, step: object = None)

Compute slice locations for input labels.

slice_locs() (start: object = None, end: object = None, step: object = None)

Compute slice locations for input labels.

snap() (freq: str = 'S')

Snap time stamps to nearest occurring frequency.

sort() (ascending: bool = True)

Return a sorted copy of the index.

sortlevel() (level: object = None, ascending: bool = True, sort_remaining: object = None, na_position: str = 'first')

Sort Index by level.

Code Examples#

The following examples are extracted from the test suite.

str (test_datetimeindex_str.py:72)
62def test_datetimeindex_str_call_with_data():
63    """Test DatetimeIndex.str(data) call."""
64    print("Testing DatetimeIndex.str(data) call...")
65
66    # Create a DatetimeIndex
67    dti = pandasCore.DatetimeIndex(['2020-01-01', '2020-12-31'])
68
69    # Call DatetimeIndex.str with the index as argument
70    try:
71        str_accessor = pandasCore.DatetimeIndex.str(dti)
72        print(f"  DatetimeIndex.str(dti) returned: {type(str_accessor)}")
73        print("  PASSED: DatetimeIndex.str(data) call works")
74    except Exception as e:
75        # Expected to raise error since DatetimeIndex doesn't contain strings
76        print(f"  Error (expected for non-string data): {e}")
77        print("  PASSED: Appropriate error raised for non-string Index")
78
79def f_main():
80    """Main test function."""
81    print("=" * 60)
__init__ (test_datetimeindex.py:51)
41TS_2020_01_04 = TS_2020_01_01 + 3 * NS_PER_DAY
42TS_2020_01_05 = TS_2020_01_01 + 4 * NS_PER_DAY
43
44
45def test_constructor_and_properties():
46    """Test DatetimeIndex constructor and basic properties"""
47    f_print_header("Test: Constructor and Properties")
48
49    # Basic construction
50    data = [TS_2020_01_01, TS_2020_01_02, TS_2020_01_03]
51    dti = pandasCore.DatetimeIndex(data, name="test_dti")
52
53    ctx.assert_equal(3, dti.size, "size")
54    ctx.assert_equal("test_dti", dti.name, "name")
55    ctx.assert_equal("datetime64[ns]", dti.dtype, "dtype")
56    ctx.assert_false(dti.empty, "empty")
57    ctx.assert_true(dti.is_unique, "is_unique")
58    ctx.assert_equal(1, dti.ndim, "ndim")
59    ctx.assert_equal((3,), dti.shape, "shape")
60    ctx.assert_equal(1, dti.nlevels, "nlevels")