Python Pandas

Pandas DatetimeIndex

In Python, various libraries and modules are utilized for working with date and time data, including the Pandas library. It can work with time series data, which is a series of data points in time order. Pandas have a special feature called DatetimeIndex, which helps store and access datetime objects easily. It is a method that changes this column into an index column and makes the date an index in the DataFrame.

In this article, we will learn how to construct DatetimeIndex as well as access/call the date and time details individually utilizing date and time methods.

What is the “pandas.DatetimeIndex()” in Python?

The pandas.DatetimeIndex() class in Python is used to create a fixed list of dates and times that cannot be changed. It is used for working with time series data and doing different things with dates and times. This method allows us to access or analyze the data at a specific date, year, month, and time or range of dates without going through the entire DataFrame.

We can also use it to make a list of dates, filter data by time, change how often data is shown, and see details about dates and times.

Syntax

pandas.DatetimeIndex(data=None, normalize=False, closed=None, yearfirst=False, dtype=None, copy=False, freq=_NoDefault.no_default, tz=_NoDefault.no_default, ambiguous='raise', dayfirst=False, name=None)

Parameters

  • The “data” parameter is the array-like datetime object that is used to construct the index.
  • The “freq” parameter specifies the index frequency. It can be set using pandas date offset strings or related objects.
  • The “tz” parameter represents the time zone of data, which can be specified using pytz.timezone, dateutil.tz.tzfile, datetime.tzinfo or str object.
  • The “normalize” is a Boolean parameter that specifies whether to normalize the beginning and end dates to midnight before creating the date range.
  • The “closed” parameter indicates whether to contain the beginning and end dates that are on the boundary of the date range.

This official pandas.DatetimeIndex documentation has more info and examples about this syntax.

Return Value
The return value of the pandas.DatetimeIndex() method is a DatetimeIndex object.

The DatetimeIndex object has several attributes that you can use to access the data and metadata associated with it. Some of the most common attributes include:

  • values: The underlying array of datetime64 data.
  • freq: The DatetimeIndex frequency.
  • start: The start date of the DatetimeIndex.
  • end: The end date of the DatetimeIndex.
  • is_monotonic: Whether the DatetimeIndex is monotonically increasing or decreasing.
  • is_unique: Whether the DatetimeIndex is unique.

Example 1: Create the DatetimeIndex Using the “pandas.DatetimeIndex()” With Hours and Week as Frequency
Let’s understand this by the following code example:

import pandas
date_obj = pandas.DatetimeIndex(['2023-02-11 05:11:00','2023-02-11 06:11:00'],dtype='datetime64[ns]',freq='H')
print('DatetimeIndex with Hours as Frequency:\n\n',date_obj)

date_obj1 = pandas.DatetimeIndex(['2023-1-1 04:11:00', '2023-1-8 04:11:00',
                                  '2023-1-15 04:11:00','2023-1-22 04:11:00'],freq='W')
print('\nDatetimeIndex with Week as Frequency:\n\n',date_obj1)

In the above code:

  • The “pandas” module is imported, and the DatetimeIndex object is created from a list of two datetime strings.
  • The “freq” argument is set to “H” to specify that the frequency of the DatetimeIndex object should be hourly.
  • Finally, we created a second DatetimeIndex object from a list of four datetime strings. Here, the “freq” argument is set to “W” to specify that the frequency of the DatetimeIndex object should be weekly.

Output

The DatetimeIndex objects have been created successfully.

Example 2: Getting the Date Details Using Various Attributes of “pandas.DatetimeIndex()”
Here, the “pandas.DatetimeIndex()” method is used along with various attributes to get the date details:

import pandas
datetime_obj = pandas.DatetimeIndex(['2023-1-1 04:11:00', '2023-1-8 04:11:00',
                                     '2023-1-15 04:11:00','2023-1-22 04:11:00'],freq='W')
print("Year:",datetime_obj.year)
print("\nMonth:",datetime_obj.month)
print("\nName of the month:",datetime_obj.month_name)
print("\nDay: ",datetime_obj.day)
print("\nDate: ",datetime_obj.date)

According to the above code:

  • The “pandas” module is imported, and the DatetimeIndex object is created with the frequency set to week.
  • The “year”, “month”, “day”, and “date” attribute is used to retrieve the date details from the DatetimeIndex results.

Output

The year, month, day, and date values have been retrieved successfully.

Example 3: Getting the Time Details Using Various Attributes of “pandas.DatetimeIndex()”
Let’s overview the following/below code:

import pandas
datetime_obj = pandas.DatetimeIndex(['2023-1-1 04:11:00', '2023-1-8 04:11:00',
                                     '2023-1-15 04:11:00','2023-1-22 04:11:00'],freq='W')
print("Hour:",datetime_obj.hour)
print("\nMinute:",datetime_obj.minute)
print("\nSecond: ",datetime_obj.second)
print("\nTime: ",datetime_obj.time)

Here:

  • The “pandas.DatetimeIndex()” method creates the DatetimeIndex object with “Week” as a frequency.
  • The “DatetimeIndex” object attributes such as hour, minute, second, and time are used to retrieve the specified time details.

Output

The time details have been retrieved from the input DatetimeIndex object.

Example 4: Determining the First and Last Day of the Month Using “pandas.DatetimeIndex()”
The below-code finds the first and last month’s day using the “is_month_start” and “is_month_end” parameter:

import pandas
datetime_obj = pandas.DatetimeIndex(['2023-1-1 04:11:00', '2023-1-8 04:11:00','2023-1-15 04:11:00','2023-1-22 04:11:00','2023-1-29 04:11:00'],freq='W')
print(datetime_obj.is_month_start)
print(datetime_obj.is_month_end)

Here, the “is_month_start” and “is_month_end” attributes of “pandas.DatetimeIndex” are used to retrieve the Boolean True and False based on the Datetime object.

Output

The month’s start and end day have been determined based on the Boolean value shown above.

Conclusion

In Python, the Pandas DatetimeIndex is a special type of index that can store and manipulate datetime objects in a Pandas DataFrame or Series. A DatetimeIndex has many attributes and methods that are used to access and modify the date and time components of the index, such as year, month, day, hour, and minute. This tutorial delivered a detailed guide on Python Pandas DatetimeIndex using numerous examples.

About the author

Haroon Javed

Hi, I'm Haroon. I am an electronics engineer and a technical content writer. I am a tech geek who loves to help people to the best of my knowledge.