C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Pandas Time PeriodsThe 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 conversionWe 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:import pandas as pd x = pd.Period('2014', freq='S') x.asfreq('D', 'start') Output: Period('2014-01-01', 'D') Example:import pandas as pd x = pd.Period('2014', freq='S') x.asfreq('D', 'end') Output: Period('2014-01-31', 'D') Period arithmeticPeriod arithmetic is used to perform various arithmetic operation on periods. All the operations will be performed on the basis of 'freq'. import pandas as pd x = pd.Period('2014', freq='Q') x Output: Period('2014', 'Q-DEC') Example:import pandas as pd x = pd.Period('2014', freq='Q') x + 1 Output: Period('2015', 'Q-DEC') Creating period rangeWe can create the range of period by using the 'period_range' command. import pandas as pd p = pd.period_range('2012', '2017', freq='A') p 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 periodIf 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. # dates as string p = ['2012-06-05', '2011-07-09', '2012-04-06'] # convert string to date format x = pd.to_datetime(p) x Output: DatetimeIndex(['2012-06-05', '2011-07-09', '2012-04-06'], dtype='datetime64[ns]', freq=None) Convert periods to timestampsIf we convert periods back to timestamps, we can simply do it by using 'to_timestamp' command. import pandas as pd prd prd.to_timestamp() Output: DatetimeIndex(['2017-04-02', '2016-04-06', '2016-05-08'], dtype='datetime64[ns]', freq=None)
Next TopicConvert string to date
|