Python Pandas - Create a datetime with DateTimeIndex

A DateTimeIndex is a pandas data structure for handling time series data. You can create a datetime series using pd.date_range() with customizable periods, frequency, and timezone settings.

Basic DateTimeIndex Creation

First, import the required library −

import pandas as pd

Creating a DateTimeIndex with date_range()

Create a DateTimeIndex with 8 periods, monthly frequency, and Australia/Sydney timezone −

import pandas as pd

# Create DateTimeIndex with period 8 and frequency as M (months)
# timezone is Australia/Sydney
datetime = pd.date_range('2021-09-24 02:35:55', periods=8, tz='Australia/Sydney', freq='M')

# Display the datetime
print("DateTime...\n", datetime)
DateTime...
 DatetimeIndex(['2021-09-30 02:35:55+10:00', '2021-10-31 02:35:55+11:00',
               '2021-11-30 02:35:55+11:00', '2021-12-31 02:35:55+11:00',
               '2022-01-31 02:35:55+11:00', '2022-02-28 02:35:55+11:00',
               '2022-03-31 02:35:55+11:00', '2022-04-30 02:35:55+10:00'],
              dtype='datetime64[ns, Australia/Sydney]', freq='M')

Extracting Date Components

You can extract various components from the DateTimeIndex −

import pandas as pd

datetime = pd.date_range('2021-09-24 02:35:55', periods=8, tz='Australia/Sydney', freq='M')

# Get the day name
print("Day names:\n", datetime.day_name())

# Get the month name  
print("\nMonth names:\n", datetime.month_name())

# Get the year
print("\nYears:\n", datetime.year)

# Get the hour
print("\nHours:\n", datetime.hour)

# Get the minutes
print("\nMinutes:\n", datetime.minute)

# Get the seconds
print("\nSeconds:\n", datetime.second)
Day names:
 Index(['Thursday', 'Sunday', 'Tuesday', 'Friday', 'Monday', 'Monday',
       'Thursday', 'Saturday'],
      dtype='object')

Month names:
 Index(['September', 'October', 'November', 'December', 'January', 'February',
       'March', 'April'], dtype='object')

Years:
 Int64Index([2021, 2021, 2021, 2021, 2022, 2022, 2022, 2022], dtype='int64')

Hours:
 Int64Index([2, 2, 2, 2, 2, 2, 2, 2], dtype='int64')

Minutes:
 Int64Index([35, 35, 35, 35, 35, 35, 35, 35], dtype='int64')

Seconds:
 Int64Index([55, 55, 55, 55, 55, 55, 55, 55], dtype='int64')

Key Parameters

Parameter Description Example
start Starting date '2021-09-24'
periods Number of periods 8
freq Frequency (D=day, M=month, Y=year) 'M'
tz Timezone 'Australia/Sydney'

Conclusion

Use pd.date_range() to create DateTimeIndex objects with customizable periods, frequency, and timezones. The resulting index provides easy access to date components like day names, months, and years for time series analysis.

Updated on: 2026-03-26T17:25:38+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements