Time Series Indexes—Attributes
Learn about the different attributes of time series objects in pandas.
Introduction
Now that we know the basic capabilities of time series indexes, let’s delve deeper into understanding their attributes, which provide us with valuable time-based information.
Like before, we’ll use the DatetimeIndex
object to represent time series indexes in this lesson due to its ubiquity in real-world use cases. Nonetheless, many of the properties seen in DatetimeIndex
are also available in the other two indexes, TimedeltaIndex
and PeriodIndex
.
We’ll use the New Delhi daily climate time series dataset for the examples in this lesson.
Preview of New Delhi Daily Climate Time Series Data
date | meantemp | humidity | wind_speed | meanpressure |
1/1/2017 | 15.91304348 | 85.86956522 | 2.743478261 | 59 |
2/1/2017 | 18.5 | 77.22222222 | 2.894444444 | 1018.277778 |
3/1/2017 | 17.11111111 | 81.88888889 | 4.016666667 | 1018.333333 |
4/1/2017 | 18.7 | 70.05 | 4.545 | 1015.7 |
5/1/2017 | 18.38888889 | 74.94444444 | 3.3 | 1014.333333 |
The DatetimeIndex
attributes
The DatetimeIndex
object comes with numerous attributes that make it easy to extract and understand the time-based information contained within it.
Core attributes
The core attributes are the basic ones that we should already be familiar with, ranging from year
to nanosecond
. In addition, the date
and time
attributes return the NumPy
array of the datetime.date
object and datetime.time
object respectively. The following code illustrates the output of these attribute calls on a subset dataset, which contains only the first row:
# Set DatetimeIndexdf['date'] = pd.to_datetime(df['date'], format='%d/%m/%Y')df = df.set_index('date')# Filter to keep only first row (for cleaner illustration purposes)df = df.head(1)# View core attributesprint('Display row:\n', df)print('='* 70)print('Year:', df.index.year)print('Month:', df.index.month)print('Day:', df.index.day)print('Hour:', df.index.hour)print('Minute:', df.index.minute)print('Second:', df.index.second)print('Microsecond:', df.index.microsecond)print('Nanosecond:', df.index.nanosecond)print('Date:', df.index.date)print('Time:', df.index.time)