Pandas: Convert index to datetime

Learn, how to convert index to datetime in Python Pandas? By Pranit Sharma Last updated : September 24, 2023

Datetime is a library in python which is a collection of date and time. Inside Datetime, we can access date and time in any format, but usually, the date is present in the format of "yy-mm-dd" and the time is present in the format of "HH:MM:SS".

Here,

  • yy means year
  • mm means month
  • dd means day
  • HH means hours
  • MM means minutes
  • SS means seconds

While accessing the date and time from DateTime, we always get date and time together, here we are going to learn how to convert the index to DateTime.

Converting index to datetime

For this purpose, we will first create a string of dates and values and read them in the form of the table by using pandas.read_table() method. Then we will convert all the indexes to datetime using pandas.to_datetime(). We can also extract hours and minutes from this datatime.

Note

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example,

Python program to convert Pandas index to datetime

# Importing pandas package
import pandas as pd

# Importing IO library
import io

# Creating a string
d = """value          
"2014-09-25 00:46"    89.02221
"2015-10-18 00:47"    39.66000
"2016-11-19 00:48"    16.32333
"2017-12-20 00:49"    88.70029
"2018-10-21 00:50"    27.09252"""

# Reading d as in table
df = pd.read_table(io.StringIO(d), delim_whitespace=True)

# Display original DataFrame
print("Original DataFrame:\n",df,"\n")

# converting index as datetime
df.index = pd.to_datetime(df.index)

# Extract hour, minute and store it another column
df['Hour'] = df.index.hour
df['Minute'] = df.index.minute

# Display modified DataFrame
print("Modified DataFrame:\n",df)

Output

The output of the above program is:

Example: Convert index to datetime

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.