Pandas Time Periods
The Time Periods represent the time span, e.g., days, years, quarter or month, etc. It is defined as a class that allows us to convert the frequency to the periods.
Generating periods and frequency conversion
We can generate the period by using ‘Period‘ command with frequency ‘M‘. If we use ‘asfreq‘ operation with ‘start‘ operation, the date will print ‘01‘ whereas if we use the ‘end‘ option, the date will print ‘31‘.
Example:
Output:
Period('2014-01-01', 'D')
Example:
Output:
Period('2014-01-31', 'D')
Period arithmetic
Period arithmetic is used to perform various arithmetic operation on periods. All the operations will be performed on the basis of ‘freq‘.
Output:
Period('2014', 'Q-DEC')
Example:
Output:
Period('2015', 'Q-DEC')
Creating period range
We can create the range of period by using the ‘period_range‘ command.
Output:
PeriodIndex(['2012-01-02', '2012-01-03', '2012-01-04', '2012-01-05', '2012-01-06', '2012-01-09', '2012-01-10', '2012-01-11', '2012-01-12', '2012-01-13', '2016-12-20', '2016-12-21', '2016-12-22', '2016-12-23', '2016-12-26', '2016-12-27', '2016-12-28', '2016-12-29', '2016-12-30', '2017-01-02'], dtype='period[B]', length=1306, freq='B')
Converting string-dates to period
If we want to Convert the string-dates to period, first we need to convert the string to date format and then we can convert the dates into the periods.
Output:
DatetimeIndex(['2012-06-05', '2011-07-09', '2012-04-06'], dtype='datetime64[ns]', freq=None)
Convert periods to timestamps
If we convert periods back to timestamps, we can simply do it by using ‘to_timestamp‘ command.
Output:
DatetimeIndex(['2017-04-02', '2016-04-06', '2016-05-08'], dtype='datetime64[ns]', freq=None)