Pandas: How to Convert Index to Datetime


You can use the following syntax to convert an index column of a pandas DataFrame to a datetime format:

df.index = pd.to_datetime(df.index)

The following example shows how to use this syntax in practice.

Example: Convert Index Column to Datetime in Pandas

Suppose we have the following pandas DataFrame that contains information about product sales at some store:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'time': ['4-15-2022 10:15', '5-19-2022 7:14', '8-01-2022 1:14',
                            '6-14-2022 9:45', '10-24-2022 2:58', '12-13-2022 11:03'],
                   'product': ['A', 'B', 'C', 'D', 'E', 'F'],
                   'sales': [12, 25, 23, 18, 14, 10]})

#set 'time' column as index
df = df.set_index('time')

#view DataFrame
print(df)

                 product  sales
time                           
4-15-2022 10:15        A     12
5-19-2022 7:14         B     25
8-01-2022 1:14         C     23
6-14-2022 9:45         D     18
10-24-2022 2:58        E     14
12-13-2022 11:03       F     10

Now suppose we attempt to create a new column that contains the hour of the time in the index column:

#attempt to create new column that contains hour of index column
df['hour'] = df.index.hour

AttributeError: 'Index' object has no attribute 'hour'

We receive an error because the index column is not currently in a datetime format so it doesn’t contain an ‘hour’ attribute.

To avoid this error, we can use the pandas to_datetime() function to convert the index column to a datetime format:

#convert index column to datetime format
df.index = pd.to_datetime(df.index)

#create new column that contains hour of index column
df['hour'] = df.index.hour

#view updated DataFrame
print(df)

                    product  sales  hour
time                                    
2022-04-15 10:15:00       A     12    10
2022-05-19 07:14:00       B     25     7
2022-08-01 01:14:00       C     23     1
2022-06-14 09:45:00       D     18     9
2022-10-24 02:58:00       E     14     2
2022-12-13 11:03:00       F     10    11

By using the to_datetime() function, we’re able to convert the index column to a datetime format.

Thus, we’re able to successfully create a new column called hour that contains the hour of the time in the index column without receiving any error.

Note: You can find the complete documentation for the pandas to_datetime() function here.

Additional Resources

The following tutorials explain how to perform other common operations in pandas:

How to Create a Date Range in Pandas
How to Convert Timestamp to Datetime in Pandas
How to Calculate a Difference Between Two Dates in Pandas

Featured Posts

Leave a Reply

Your email address will not be published. Required fields are marked *