+

Python | Pandas DatetimeIndex.year

DatetimeIndex.year Pandas DatetimeIndex.year outputs an Index object containing the value of the years present in the Datetime object .

Syntax: DatetimeIndex.year

Return: Index containing years.

Example # 1: Use the DatetimeIndex.year attribute to find the years present in the DatetimeIndex.

# import pandas as pd

import pandas as pd

 
# Create DatetimeIndex
# Here "B" represents the frequency of business days

didx = pd.DatetimeIndex (sta rt = `2014-08-01 10:00` , freq = `B`

periods = 5 , tz = `Asia / Calcutta` )

 
# Print DatetimeIndex

print (didx)

Output:

Now we want to find all the year values ​​present in the DatetimeIndex object.

# find all years in the object
didx.year

Output:

As we can see in the output, the function returned an Index object containing the year value of each record in the DatetimeIndex object. 
& amp; n bsp; 
Example # 2: Use the DatetimeIndex.year attribute to find the years present in the DatetimeIndex.

# import pandas as pd

import pandas as pd

 
# Create DatetimeIndex
# Here "AS" represents the frequency of the beginning of the year

didx = pd.DatetimeIndex (start = ` 2014-08-01 10:00` , freq = `AS`

periods =   5 , tz = `Asia / Calcutta` )

 
# Print DatetimeIndex

print (didx)

Output:

Now we want to find all the year values ​​present in the DatetimeIndex object.

# find all years in the object
didx.year

Output:

As we can see in the output, the function returned the volume kt Index containing the year value of each record in the DatetimeIndex object.

Get Solution for free from DataCamp guru