pandas contains extensive capabilities and features for working with time series data for all domains.
Using the NumPy datetime64 and timedelta64 dtypes, pandas has consolidated a large number of
features from other Python libraries like scikits.timeseries as well as created
a tremendous amount of new functionality for manipulating time series data.
For example, pandas supports:
Parsing time series information from various sources and formats
In [1]: importdatetimeIn [2]: dti=pd.to_datetime( ...:
Performing date and time arithmetic with absolute or relative time increments
In [13]: friday=pd.Timestamp("2018-01-05")In [14]: friday.day_name()Out[14]: 'Friday'# Add 1 dayIn [15]: saturday=friday+pd.Timedelta("1 day")In [16]: saturday.day_name()Out[16]: 'Saturday'# Add 1 business day (Friday --> Monday)In [17]: monday=friday+pd.offsets.BDay()In [18]: monday.day_name()Out[18]: 'Monday'
pandas provides a relatively compact and self-contained set of tools for
performing the above tasks and more.
Overview
pandas captures 4 general time related concepts:
Date times: A specific date and time with timezone support. Similar to datetime.datetime from the standard library.
Time deltas: An absolute time duration. Similar to datetime.timedelta from the standard library.
Time spans: A span of time defined by a point in time and its associated frequency.
Date offsets: A relative time duration that respects calendar arithmetic. Similar to dateutil.relativedelta.relativedelta from the dateutil package.
Concept
Scalar Class
Array Class
pandas Data Type
Primary Creation Method
Date times
Timestamp
DatetimeIndex
datetime64[ns] or datetime64[ns,tz]
to_datetime or date_range
Time deltas
For time series data, it’s conventional to represent the time component in the index of a Series or DataFrame
so manipulations can be performed with respect to the time element.
In [19]: pd.Series(range(3),index=pd.date_range("2000",freq="D",periods=3))Out[19]: 2000-01-01 02000-01-02 12000-01-03 2Freq: D, dtype: int64
However, Series and DataFrame can directly also support the time component as data itself.
In [20]: pd.Series(pd.date_range("2000",freq="D",periods=3))Out[20]: 0 2000-01-011 2000-01-022 2000-01-03dtype: datetime64[ns]
Series and DataFrame have extended data type support and functionality for datetime, timedelta
and Period data when passed into those constructors. DateOffset
data however will be stored as object data.
In [21]: pd.Series(pd.period_range("1/1/2011",freq="M",periods=3))Out[21]: 0 2011-011 2011-022 2011-03dtype: period[M]In [22]: pd.Series([pd.DateOffset(1),pd.
Lastly, pandas represents null date times, time deltas, and time spans as NaT which
is useful for representing missing or null date like values and behaves similar
as np.nan does for float data.
In [24]: pd.Timestamp(pd.NaT)Out[24]: NaTIn [25]: pd.Timedelta(pd.NaT)Out[25]: NaTIn [26]: pd.Period(pd.NaT)Out[26]: NaT# Equality acts as np.nan wouldIn [27]: pd.
Timestamps vs. time spans
Timestamped data is the most basic type of time series data that associates
values with points in time. For pandas objects it means using the points in
time.
However, in many cases it is more natural to associate things like change
variables with a time span instead. The span represented by Period can be
specified explicitly, or inferred from datetime string format.
For example:
In [32]: pd.Period("2011-01")Out[32]: Period('2011-01', 'M')In [33]: pd.Period("2012-05",freq="D")Out[33]: Period('2012-05-01', 'D')
In [34]: dates=[ ....: pd.Timestamp("2012-05-01"), ....: pd.Timestamp("2012-05-02"), ....: pd.Timestamp("2012-05-03"), ....: ] ....: In [35]: ts=pd.Series(np
pandas allows you to capture both representations and
convert between them. Under the hood, pandas represents timestamps using
instances of Timestamp and sequences of timestamps using instances of
DatetimeIndex. For regular time spans, pandas uses Period objects for
scalar values and PeriodIndex for sequences of spans. Better support for
irregular intervals with arbitrary start and end points are forth-coming in
future releases.
Converting to timestamps
To convert a Series or list-like object of date-like objects e.g. strings,
epochs, or a mixture, you can use the to_datetime function. When passed
a Series, this returns a Series (with the same index), while a list-like
is converted to a DatetimeIndex:
If you pass a single string to to_datetime, it returns a single Timestamp.
Timestamp can also accept string input, but it doesn’t accept string parsing
options like dayfirst or format, so use to_datetime if these are required.
In [48]: pd.to_datetime("2010/11/12")Out[48]: Timestamp('2010-11-12 00:00:00')In [49]: pd.Timestamp("2010/11/12")Out[49]: Timestamp('2010-11-12 00:00:00')
You can also use the DatetimeIndex constructor directly:
In [50]: pd.DatetimeIndex(["2018-01-01","2018-01-03","2018-01-05"])Out[50]: DatetimeIndex(['2018-01-01', '2018-01-03', '2018-01-05'], dtype='datetime64[ns]', freq=None)
The string ‘infer’ can be passed in order to set the frequency of the index as the
inferred frequency upon creation:
In [51]: pd.DatetimeIndex(["2018-01-01","2018-01-03","2018-01-05"],freq="infer")Out[51]: DatetimeIndex(['2018-01-01', '2018-01-03', '2018-01-05'], dtype='datetime64[ns]', freq='2D')
Providing a format argument
In addition to the required datetime string, a format argument can be passed to ensure specific parsing.
This could also potentially speed up the conversion considerably.
In [52]: pd.to_datetime("2010/11/12",format="%Y/%m/%d")Out[52]: Timestamp('2010-11-12 00:00:00')In [53]: pd.to_datetime("12-11-2010 00:00",format="
Assembling datetime from multiple DataFrame columns
You can also pass a DataFrame of integer or string columns to assemble into a Series of Timestamps.
In [54]: df=pd.DataFrame( ....: {"year":[2015,2016],"month":[2,
Invalid data
The default behavior, errors='raise', is to raise when unparsable:
In [57]: pd.to_datetime(['2009/07/31','asd'],errors='raise')---------------------------------------------------------------------------ValueErrorTraceback (most recent call last)
CellIn[57],line1----> 1pd.to_datetime
in
in
in
in
in
in
: time data "asd" doesn't match format "%Y/%m/%d", at position 1. You might want to try:
Epoch timestamps
pandas supports converting integer or float epoch times to Timestamp and
DatetimeIndex. The default unit is nanoseconds, since that is how Timestamp
objects are stored internally. However, epochs are often stored in another unit
which can be specified. These are computed from the starting point specified by the
origin parameter.
In [59]: pd.to_datetime( ....: [1349720105,1349806505,1349892905
From timestamps to epoch
To invert the operation from above, namely, to convert from a Timestamp to a ‘unix’ epoch:
Using the origin parameter, one can specify an alternative starting point for creation
of a DatetimeIndex. For example, to use 1960-01-01 as the starting date:
In [68]: pd.to_datetime([1,2,3],unit="D",origin=pd.Timestamp(
Generating ranges of timestamps
To generate an index with timestamps, you can use either the DatetimeIndex or
Index constructor and pass in a list of datetime objects:
In [70]: dates=[ ....: datetime.datetime(2012,5,1), ....: datetime.datetime(2012,5,2), ....: datetime.datetime(2012,5,3), ....: ] ....: # Note the frequency informationIn [71]: index=pd.DatetimeIndex(dates)In [72]: indexOut[72]: DatetimeIndex(['2012-05-01', '2012-05-02', '2012-05-03'], dtype='datetime64[ns]', freq=None)# Automatically converted to DatetimeIndexIn [73]: index=pd.Index(dates)In [74]: indexOut[74]: DatetimeIndex(['2012-05-01', '2012-05-02', '2012-05-03'], dtype='datetime64[ns]', freq=None)
In practice this becomes very cumbersome because we often need a very long
index with a large number of timestamps. If we need timestamps on a regular
frequency, we can use the date_range() and bdate_range() functions
to create a DatetimeIndex. The default frequency for date_range is a
calendar day while the default for bdate_range is a business day:
In [75]: start=datetime.datetime(2011,1,1)In [76]: end=datetime.datetime(2012,1,1)In [77]: index=pd.date_range(start,end)In [78]:
Convenience functions like date_range and bdate_range can utilize a
variety of frequency aliases:
date_range and bdate_range make it easy to generate a range of dates
using various combinations of parameters like start, end, periods,
and freq. The start and end dates are strictly inclusive, so dates outside
of those specified will not be generated:
Specifying start, end, and periods will generate a range of evenly spaced
dates from start to end inclusively, with periods number of elements in the
resulting DatetimeIndex:
bdate_range can also generate a range of custom frequency dates by using
the weekmask and holidays parameters. These parameters will only be
used if a custom frequency string is passed.
In [89]: weekmask="Mon Wed Fri"In [90]: holidays=[datetime.datetime(2011,1,5),datetime
Timestamp limitations
The limits of timestamp representation depend on the chosen resolution. For
nanosecond resolution, the time span that
can be represented using a 64-bit integer is limited to approximately 584 years:
In [93]: pd.Timestamp.minOut[93]: Timestamp('1677-09-21 00:12:43.145224193')In [94]: pd.Timestamp.maxOut[94]: Timestamp('2262-04-11 23:47:16.854775807')
When choosing second-resolution, the available range grows to +/-2.9e11years.
Different resolutions can be converted to each other through as_unit.
Indexing
One of the main uses for DatetimeIndex is as an index for pandas objects.
The DatetimeIndex class contains many time series related optimizations:
A large range of dates for various offsets are pre-computed and cached
under the hood in order to make generating subsequent date ranges very fast
(just have to grab a slice).
Fast shifting using the shift method on pandas objects.
Unioning of overlapping DatetimeIndex objects with the same frequency is
very fast (important for fast data alignment).
Quick access to date fields via properties such as year, month, etc.
Regularization functions like snap and very fast asof logic.
DatetimeIndex objects have all the basic functionality of regular Index
objects, and a smorgasbord of advanced time series specific methods for easy
frequency processing.
DatetimeIndex can be used like a regular index and offers all of its
intelligent functionality like selection, slicing, etc.
In [95]: rng=pd.date_range(start,end,freq="BME")In [96]: ts=pd.Series(np.random.randn(len(rng)),index=rng)In [97]: ts
Partial string indexing
Dates and strings that parse to timestamps can be passed as indexing parameters:
The same string used as an indexing parameter can be treated either as a slice or as an exact match depending on the resolution of the index. If the string is less accurate than the index, it will be treated as a slice, otherwise as an exact match.
Consider a Series object with a minute resolution index:
In [121]: series_minute=pd.Series( .....: [1,2,3], .....: pd.DatetimeIndex( .....: ["2011-12-31 23:59:00"
Exact indexing
As discussed in previous section, indexing a DatetimeIndex with a partial string depends on the “accuracy” of the period, in other words how specific the interval is in relation to the resolution of the index. In contrast, indexing with Timestamp or datetime objects is exact, because the objects have exact meaning. These also follow the semantics of including both endpoints.
These Timestamp and datetime objects have exact hours,minutes, and seconds, even though they were not explicitly specified (they are 0).
Truncating & fancy indexing
A truncate() convenience function is provided that is similar
to slicing. Note that truncate assumes a 0 value for any unspecified date
component in a DatetimeIndex in contrast to slicing which returns any
partially matching dates:
In [137]: rng2=pd.date_range("2011-01-01","2012-01-01",freq="W")In [138]: ts2
Time/date components
There are several time/date properties that one can access from Timestamp or a collection of timestamps like a DatetimeIndex.
Property
Description
year
The year of the datetime
month
The month of the datetime
day
The days of the datetime
hour
The hour of the datetime
minute
The minutes of the datetime
second
The seconds of the datetime
microsecond
The microseconds of the datetime
nanosecond
The nanoseconds of the datetime
date
Returns datetime.date (does not contain timezone information)
time
Returns datetime.time (does not contain timezone information)
timetz
Returns datetime.time as local time with timezone information
dayofyear
The ordinal day of year
day_of_year
The ordinal day of year
weekofyear
The week ordinal of the year
week
The week ordinal of the year
dayofweek
The number of the day of the week with Monday=0, Sunday=6
day_of_week
The number of the day of the week with Monday=0, Sunday=6
weekday
The number of the day of the week with Monday=0, Sunday=6
quarter
Quarter of the date: Jan-Mar = 1, Apr-Jun = 2, etc.
days_in_month
The number of days in the month of the datetime
is_month_start
Logical indicating if first day of month (defined by frequency)
is_month_end
Logical indicating if last day of month (defined by frequency)
is_quarter_start
Logical indicating if first day of quarter (defined by frequency)
is_quarter_end
Logical indicating if last day of quarter (defined by frequency)
is_year_start
Logical indicating if first day of year (defined by frequency)
is_year_end
Logical indicating if last day of year (defined by frequency)
is_leap_year
Logical indicating if the date belongs to a leap year
Furthermore, if you have a Series with datetimelike values, then you can
access these properties via the .dt accessor, as detailed in the section
on .dt accessors.
You may obtain the year, week and day components of the ISO year from the ISO 8601 standard:
These frequency strings map to a DateOffset object and its subclasses. A DateOffset
is similar to a Timedelta that represents a duration of time but follows specific calendar duration rules.
For example, a Timedelta day will always increment datetimes by 24 hours, while a DateOffset day
will increment datetimes to the same time the next day whether a day represents 23, 24 or 25 hours due to daylight
savings time. However, all DateOffset subclasses that are an hour or smaller
(Hour, Minute, Second, Milli, Micro, Nano) behave like
Timedelta and respect absolute time.
The basic DateOffset acts similar to dateutil.relativedelta (relativedelta documentation)
that shifts a date time by the corresponding calendar duration specified. The
arithmetic operator (+) can be used to perform the shift.
# This particular day contains a day light savings time transitionIn [145]: ts=pd.Timestamp("2016-10-30 00:00:00",tz="Europe/Helsinki")# Respects absolute timeIn [146]: ts+pd.Timedelta(days=1)Out[146]: Timestamp('2016-10-30 23:00:00+0200', tz='Europe/Helsinki')# Respects calendar timeIn [147]: ts+pd.DateOffset
Most DateOffsets have associated frequencies strings, or offset aliases, that can be passed
into freq keyword arguments. The available date offsets and associated frequency strings can be found below:
Generic offset class, defaults to absolute 24 hours
or
DateOffsets additionally have rollforward() and rollback()
methods for moving a date forward or backward respectively to a valid offset
date relative to the offset. For example, business offsets will roll dates
that land on the weekends (Saturday and Sunday) forward to Monday since
business offsets operate on the weekdays.
In [153]: ts=pd.Timestamp("2018-01-06 00:00:00")In [154]: ts.day_name()Out[154]: 'Saturday'# BusinessHour's valid offset dates are Monday through FridayIn [155]: offset=pd.offsets.BusinessHour(start="09:00")# Bring the date to the closest offset date (Monday)In [156]: offset.rollforward
These operations preserve time (hour, minute, etc) information by default.
To reset time to midnight, use normalize() before or after applying
the operation (depending on whether you want the time information included
in the operation).
Some of the offsets can be “parameterized” when created to result in different
behaviors. For example, the Week offset for generating weekly data accepts a
weekday parameter which results in the generated dates always lying on a
particular day of the week:
Offsets can be used with either a Series or DatetimeIndex to
apply the offset to each element.
In [177]: rng=pd.date_range("2012-01-01","2012-01-03")In [178]: s=pd.Series(
Custom business days
The CDay or CustomBusinessDay class provides a parametric
BusinessDay class which can be used to create customized business day
calendars which account for local holidays and local weekend conventions.
As an interesting example, let’s look at Egypt where a Friday-Saturday weekend is observed.
In [188]: weekmask_egypt="Sun Mon Tue Wed Thu"# They also observe International Workers' Day so let's# add that for a couple of yearsIn [189]: holidays=[ .....: "2012-05-01", .....: datetime
Business hour
The BusinessHour class provides a business hour representation on BusinessDay,
allowing to use specific start and end times.
By default, BusinessHour uses 9:00 - 17:00 as business hours.
Adding BusinessHour will increment Timestamp by hourly frequency.
If target Timestamp is out of business hours, move to the next business hour
then increment it. If the result exceeds the business hours end, the remaining
hours are added to the next business day.
In [203]: bh=pd.offsets.
Custom business hour
The CustomBusinessHour is a mixture of BusinessHour and CustomBusinessDay which
allows you to specify arbitrary holidays. CustomBusinessHour works as the same
as BusinessHour except that it skips specified custom holidays.
In [228]: frompandas.tseries.holidayimportUSFederalHolidayCalendarIn [229]: bhour_us=pd.offsets
Offset aliases
A number of string aliases are given to useful common time series
frequencies. We will refer to these aliases as offset aliases.
Alias
Description
B
business day frequency
C
custom business day frequency
D
Period aliases
A number of string aliases are given to useful common time series
frequencies. We will refer to these aliases as period aliases.
Alias
Description
B
business day frequency
D
calendar day frequency
W
Combining aliases
As we have seen previously, the alias and the offset instance are fungible in
most functions:
For some frequencies you can specify an anchoring suffix:
Alias
Description
W-SUN
weekly frequency (Sundays). Same as ‘W’
W-MON
weekly frequency (Mondays)
W-TUE
weekly frequency (Tuesdays)
Anchored offset semantics
For those offsets that are anchored to the start or end of specific
frequency (MonthEnd, MonthBegin, WeekEnd, etc), the following
rules apply to rolling forward and backwards.
When n is not 0, if the given date is not on an anchor point, it snapped to the next(previous)
anchor point, and moved |n|-1 additional steps forwards or backwards.
In [243]: pd.Timestamp("2014-01-02")+pd.offsets.
Holidays / holiday calendars
Holidays and calendars provide a simple way to define holiday rules to be used
with CustomBusinessDay or in other analysis that requires a predefined
set of holidays. The AbstractHolidayCalendar class provides all the necessary
methods to return a list of holidays and only rules need to be defined
in a specific holiday calendar class. Furthermore, the start_date and end_date
class attributes determine over what date range holidays are generated. These
should be overwritten on the AbstractHolidayCalendar class to have the range
apply to all calendar subclasses. USFederalHolidayCalendar is the
only calendar that exists and primarily serves as an example for developing
other calendars.
For holidays that occur on fixed dates (e.g., US Memorial Day or July 4th) an
observance rule determines when that holiday is observed if it falls on a weekend
or some other non-observed day. Defined observance rules are:
Time Series-related instance methods
Shifting / lagging
One may want to shift or lag the values in a time series back and forward in
time. The method for this is shift(), which is available on all of
the pandas objects.
Note that with when freq is specified, the leading entry is no longer NaN
because the data is not being realigned.
Frequency conversion
The primary function for changing frequencies is the asfreq()
method. For a DatetimeIndex, this is basically just a thin, but convenient
wrapper around reindex() which generates a date_range and
calls reindex.
DatetimeIndex can be converted to an array of Python native
datetime.datetime objects using the to_pydatetime method.
Resampling
pandas has a simple, powerful, and efficient functionality for performing
resampling operations during frequency conversion (e.g., converting secondly
data into 5-minutely data). This is extremely common in, but not limited to,
financial applications.
resample() is a time-based groupby, followed by a reduction method
on each of its groups. See some cookbook examples for
some advanced strategies.
The resample() method can be used directly from DataFrameGroupBy objects,
see the groupby docs.
The resample function is very flexible and allows you to specify many
different parameters to control the frequency conversion and resampling
operation.
Any built-in method available via GroupBy is available as
a method of the returned object, including sum, mean, std, sem,
max, min, median, first, last, ohlc:
In [293]: ts.resample("5Min").mean()Out[293]: 2012-01-01 251.03Freq: 5min, dtype: float64In [294]: ts.resample("5Min").ohlc()Out[294]: open high low close2012-01-01 308 460 9 205In [295]: ts.resample("5Min").max
For downsampling, closed can be set to ‘left’ or ‘right’ to specify which
end of the interval is closed:
Parameters like label are used to manipulate the resulting labels.
label specifies whether the result is labeled with the beginning or
the end of the interval.
In [298]: ts.resample("5Min").mean()# by default label='left'Out[298]: 2012-01-01 251.03Freq: 5min, dtype: float64In [299]: ts.resample("5Min",label="left").mean()Out[299]: 2012-01-01 251.03Freq: 5min, dtype: float64
The axis parameter can be set to 0 or 1 and allows you to resample the
specified axis for a DataFrame.
kind can be set to ‘timestamp’ or ‘period’ to convert the resulting index
to/from timestamp and time span representations. By default resample
retains the input representation.
convention can be set to ‘start’ or ‘end’ when resampling period data
(detail below). It specifies how low frequency periods are converted to higher
frequency periods.
Upsampling
For upsampling, you can specify a way to upsample and the limit parameter to interpolate over the gaps that are created:
# from secondly to every 250 millisecondsIn [305]: ts[:2].resample("250ms").asfreq()Out[305]: 2012-01-01 00:00:00.000 308.02012-01-01 00:00:00.250 NaN2012-01-01 00:00:00.500 NaN2012-01-01 00:00:00.750 NaN2012-01-01 00:00:01.000 204.0Freq: 250ms, dtype: float64In [306]: ts[:2
Sparse resampling
Sparse timeseries are the ones where you have a lot fewer points relative
to the amount of time you are looking to resample. Naively upsampling a sparse
series can potentially generate lots of intermediate values. When you don’t want
to use a method to fill these values, e.g. fill_method is None, then
intermediate values will be filled with NaN.
Since resample is a time-based groupby, the following is a method to efficiently
resample only the groups that are not all NaN.
In [308]: rng=pd.date_range("2014-1-1",periods=
Aggregation
The resample() method returns a pandas.api.typing.Resampler instance. Similar to
the aggregating API, groupby API,
and the window API, a Resampler can be selectively resampled.
Resampling a DataFrame, the default will be to act on all columns with the same function.
In [315]: df=pd.DataFrame
Iterating through groups
With the Resampler object in hand, iterating through the grouped data is very
natural and functions similarly to itertools.groupby():
Use origin or offset to adjust the start of the bins
The bins of the grouping are adjusted based on the beginning of the day of the time series starting point. This works well with frequencies that are multiples of a day (like 30D) or that divide a day evenly (like 90s or 1min). This can create inconsistencies with some frequencies that do not meet this criteria. To change this behavior you can specify a fixed Timestamp with the argument origin.
For example:
In [332]: start,end="2000-10-01 23:30:00"
Backward resample
Instead of adjusting the beginning of bins, sometimes we need to fix the end of the bins to make a backward resample with a given freq. The backward resample sets closed to 'right' by default since the last value should be considered as the edge point for the last bin.
We can set origin to 'end'. The value for a specific Timestamp index stands for the resample result from the current Timestamp minus freq to the current with a right close.
Time span representation
Regular intervals of time are represented by Period objects in pandas while
sequences of Period objects are collected in a PeriodIndex, which can
be created with the convenience function period_range.
Period
A Period represents a span of time (e.g., a day, a month, a quarter, etc).
You can specify the span via freq keyword using a frequency alias like below.
Because freq represents a span of Period, it cannot be negative like “-3D”.
Adding and subtracting integers from periods shifts the period by its own
frequency. Arithmetic is not allowed between Period with different freq (span).
If Period freq is daily or higher (D, h, min, s, ms, us, and ns), offsets and timedelta-like can be added if the result can have the same freq. Otherwise, ValueError will be raised.
In [366]: p+pd.offsets.Minute(5)---------------------------------------------------------------------------ValueErrorTraceback (most recent call last)
File ~/work/pandas/pandas/pandas/_libs/tslibs/period.pyx:1824, in pandas._libs.tslibs.period._Period._add_timedeltalike_scalar()File ~/work/pandas/pandas/pandas/_libs/tslibs/timedeltas.pyx:278, in pandas._libs.tslibs.timedeltas.delta_to_nanoseconds()File ~/work/pandas/pandas/pandas/_libs/tslibs/np_datetime.pyx:661, in pandas._libs.tslibs.np_datetime.convert_reso()ValueError: Cannot losslessly convert units
Theaboveexceptionwasthedirect
Traceback (most recent call last)
in
in
: Input cannot be converted to Period(freq=h)
If Period has other frequencies, only the same offsets can be added. Otherwise, ValueError will be raised.
In [367]: p=pd.Period("2014-07",freq="M")In [368]: p+pd.offsets.MonthEnd(3)Out[368]: Period('2014-10', 'M')
In [369]: p+pd.offsets.MonthBegin(3)---------------------------------------------------------------------------IncompatibleFrequencyTraceback (most recent call last)
CellIn[369],line1----> 1p+pd.offsets.MonthBegin(3)File ~/work/pandas/pandas/pandas/_libs/tslibs/period.pyx:1847, in pandas._libs.tslibs.period._Period.__add__
in
in
: Input has different freq=3M from Period(freq=M)
Taking the difference of Period instances with the same frequency will
return the number of frequency units between them:
In [370]: pd.Period("2012",freq="Y-DEC")-pd.Period("2002",freq="Y-DEC")Out[370]: <10 * YearEnds: month=12>
PeriodIndex and period_range
Regular sequences of Period objects can be collected in a PeriodIndex,
which can be constructed using the period_range convenience function:
PeriodIndex has a custom period dtype. This is a pandas extension
dtype similar to the timezone aware dtype (datetime64[ns,tz]).
The period dtype holds the freq attribute and is represented with
period[freq] like period[D] or period[M], using frequency strings.
PeriodIndex partial string indexing
PeriodIndex now supports partial string slicing with non-monotonic indexes.
You can pass in dates and strings to Series and DataFrame with PeriodIndex, in the same manner as DatetimeIndex. For details, refer to DatetimeIndex Partial String Indexing.
In [392]: ps["2011-01"]Out[392]: -2.9169013294054507In [393]: ps[datetime.datetime
Frequency conversion and resampling with PeriodIndex
The frequency of Period and PeriodIndex can be converted via the asfreq
method. Let’s start with the fiscal year 2011, ending in December:
In [400]: p=pd.Period("2011",freq="Y-DEC")In [401]: pOut[401]: Period('2011', 'Y-DEC')
We can convert it to a monthly frequency. Using the parameter, we can
specify whether to return the starting or ending month:
Converting between representations
Timestamped data can be converted to PeriodIndex-ed data using to_period
and vice-versa using to_timestamp:
Converting between period and timestamp enables some convenient arithmetic
functions to be used. In the following example, we convert a quarterly
frequency with year ending in November to 9am of the end of the month following
the quarter end:
In [421]: prng=pd.period_range("1990Q1","2000Q4",freq="Q-NOV")In [422]: ts=pd.Series(np.random.randn(len(prng)),prng)In [423]: ts.index
Representing out-of-bounds spans
If you have data that is outside of the Timestamp bounds, see Timestamp limitations,
then you can use a PeriodIndex and/or Series of Periods to do computations.
In [432]: span=pd.PeriodIndex(s.apply(conv))In [433]: spanOut[433]: PeriodIndex(['2012-12-31', '2014-11-30', '9999-12-31'], dtype='period[D]')
Time zone handling
pandas provides rich support for working with timestamps in different time
zones using the pytz and dateutil libraries or datetime.timezone
objects from the standard library.
Working with time zones
By default, pandas objects are time zone unaware:
In [434]: rng=pd.date_range("3/6/2012 00:00",periods=15,freq="D")In [435]: rng.tzisNoneOut[435]: True
To localize these dates to a time zone (assign a particular time zone to a naive date),
you can use the tz_localize method or the tz keyword argument in
date_range(), Timestamp, or DatetimeIndex.
You can either pass pytz or dateutil time zone objects or Olson time zone database strings.
Olson time zone strings will return pytz time zone objects by default.
To return dateutil time zone objects, append before the string.
In pytz you can find a list of common (and less common) time zones using
frompytzimportcommon_timezones,all_timezones.
dateutil uses the OS time zones so there isn’t a fixed list available. For
common zones, the names are the same as pytz.
Note that the UTC time zone is a special case in dateutil and should be constructed explicitly
as an instance of dateutil.tz.tzutc. You can also construct other time
zones objects explicitly first.
Under the hood, all timestamps are stored in UTC. Values from a time zone aware
DatetimeIndex or Timestamp will have their fields (day, hour, minute, etc.)
localized to the time zone. However, timestamps with the same UTC value are
still considered to be equal even if they are in different time zones:
Operations between Series in different time zones will yield UTC
Series, aligning the data on the UTC timestamps:
In [469]: ts_utc=pd.Series(range(3),pd.date_range("20130101",periods=3,tz="UTC"))In [470]: eastern=ts_utc.tz_convert("US/Eastern")In [471]: berlin
To remove time zone information, use tz_localize(None) or tz_convert(None).
tz_localize(None) will remove the time zone yielding the local time representation.
tz_convert(None) will remove the time zone after converting to UTC time.
For ambiguous times, pandas supports explicitly specifying the keyword-only fold argument.
Due to daylight saving time, one wall clock time can occur twice when shifting
from summer to winter time; fold describes whether the datetime-like corresponds
to the first (0) or the second time (1) the wall clock hits the ambiguous time.
Fold is supported only for constructing from naive datetime.datetime
(see datetime documentation for details) or from Timestamp
or for constructing from components (see below). Only dateutil timezones are supported
(see dateutil documentation
for dateutil methods that deal with ambiguous datetimes) as pytz
timezones do not support fold (see pytz documentation
for details on how deals with ambiguous datetimes). To localize an ambiguous datetime
with , please use . In general, we recommend to rely
on when localizing ambiguous datetimes if you need direct
control over how they are handled.
Ambiguous times when localizing
tz_localize may not be able to determine the UTC offset of a timestamp
because daylight savings time (DST) in a local time zone causes some times to occur
twice within one day (“clocks fall back”). The following options are available:
'raise': Raises a pytz.AmbiguousTimeError (the default behavior)
'infer': Attempt to determine the correct offset base on the monotonicity of the timestamps
'NaT': Replaces ambiguous times with NaT
bool: True represents a DST time, represents non-DST time. An array-like of values is supported for a sequence of times.
Nonexistent times when localizing
A DST transition may also shift the local time ahead by 1 hour creating nonexistent
local times (“clocks spring forward”). The behavior of localizing a timeseries with nonexistent times
can be controlled by the nonexistent argument. The following options are available:
'raise': Raises a pytz.NonExistentTimeError (the default behavior)
'NaT': Replaces nonexistent times with NaT
'shift_forward': Shifts nonexistent times forward to the closest real time
'shift_backward': Shifts nonexistent times backward to the closest real time
timedelta object: Shifts nonexistent times by the timedelta duration
Time zone Series operations
A Series with time zone naive values is
represented with a dtype of datetime64[ns].
In [494]: s_naive=pd.Series(pd.date_range("20130101",periods=3))In [495]: s_naiveOut[495]:
Constructing a Timestamp or DatetimeIndex with an epoch timestamp
with the tz argument specified will raise a ValueError. If you have
epochs in wall time in another timezone, you can read the epochs
as timezone-naive timestamps and then localize to the appropriate timezone:
This type of slicing will work on a DataFrame with a DatetimeIndex as well. Since the
partial string selection is a form of label slicing, the endpoints will be included. This
would include matching times on an included date:
DatetimeIndex partial string indexing also works on a DataFrame with a MultiIndex:
In [112]: dft2=pd.DataFrame( .....: np.random.randn(20,1), .....: columns=["A"], .....: index=pd.MultiIndex.from_product( .....: [pd.date_range("20130101",periods=10,freq="12h"),["a","b"]] .....: ), .....: ) .....: In [113]: dft2Out[113]: A2013-01-01 00:00:00 a -0.298694 b 0.8235532013-01-01 12:00:00 a 0.943285 b -1.4793992013-01-02 00:00:00 a -1.643342... ...2013-01-04 12:00:00 b 0.0690362013-01-05 00:00:00 a 0.122297 b 1.4220602013-01-05 12:00:00 a 0.370079 b 1.016331[20 rows x 1 columns]In [114]: dft2.loc["2013-01-05"]Out[114]: A2013-01-05 00:00:00 a 0.122297 b 1.4220602013-01-05 12:00:00 a 0.370079 b 1.016331In [115]: idx=pd.IndexSliceIn [116]: dft2=dft2.swaplevel(0,1).sort_index()In [117]: dft2.loc[idx[:,"2013-01-05"],:]Out[117]: Aa 2013-01-05 00:00:00 0.122297 2013-01-05 12:00:00 0.370079b 2013-01-05 00:00:00 1.422060 2013-01-05 12:00:00 1.016331
Slicing with string indexing also honors UTC offset.
If the offset class maps directly to a Timedelta (Day, Hour,
Minute, Second, Micro, Milli, Nano) it can be
used exactly like a Timedelta - see the
Timedelta section for more examples.
In [183]: s-pd.offsets.Day(2)Out[183]: 0 2011-12-301 2011-12-312 2012-01-01dtype: datetime64[ns]In [184]: td=s-pd.Series(pd.date_range("2011-12-29","2011-12-31"))In [185]: tdOut[185]: 0 3 days1 3 days2 3 daysdtype: timedelta64[ns]In [186]: td+pd.offsets.Minute(15)Out[186]: 0 3 days 00:15:001 3 days 00:15:002 3 days 00:15:00dtype: timedelta64[ns]
Note that some offsets (such as BQuarterEnd) do not have a
vectorized implementation. They can still be used but may
calculate significantly slower and will show a PerformanceWarning
In [187]: rng+pd.offsets.BQuarterEnd()Out[187]: DatetimeIndex(['2012-03-30', '2012-03-30', '2012-03-30'], dtype='datetime64[ns]', freq=None)
.
datetime
(
2013
,
5
,
1
),
.....:
np
.
datetime64
(
"2014-05-01"
),
.....:
]
.....:
In [190]:
bday_egypt
=
pd
.
offsets
.
CustomBusinessDay
(
.....:
holidays
=
holidays
,
.....:
weekmask
=
weekmask_egypt
,
.....:
)
.....:
In [191]:
dt
=
datetime
.
datetime
(
2013
,
4
,
30
)
In [192]:
dt
+
2
*
bday_egypt
Out[192]:
Timestamp('2013-05-05 00:00:00')
Let’s map to the weekday names:
In [193]: dts=pd.date_range(dt,periods=5,freq=bday_egypt)In [194]: pd.Series(dts.weekday,dts).map(pd.Series("Mon Tue Wed Thu Fri Sat Sun".split()))Out[194]: 2013-04-30 Tue2013-05-02 Thu2013-05-05 Sun2013-05-06 Mon2013-05-07 TueFreq: C, dtype: object
Holiday calendars can be used to provide the list of holidays. See the
holiday calendar section for more information.
In [195]: frompandas.tseries.holidayimportUSFederalHolidayCalendarIn [196]: bday_us=pd.offsets.CustomBusinessDay(calendar=USFederalHolidayCalendar())# Friday before MLK DayIn [197]: dt=datetime.datetime(2014,1,17)# Tuesday after MLK Day (Monday is skipped because it's a holiday)In [198]: dt+bday_usOut[198]: Timestamp('2014-01-21 00:00:00')
Monthly offsets that respect a certain holiday calendar can be defined
in the usual way.
In [199]: bmth_us=pd.offsets.CustomBusinessMonthBegin(calendar=USFederalHolidayCalendar())# Skip new yearsIn [200]: dt=datetime.datetime(2013,12,17)In [201]: dt+bmth_usOut[201]: Timestamp('2014-01-02 00:00:00')# Define date index with custom offsetIn [202]: pd.date_range(start="20100101",end="20120101",freq=bmth_us)Out[202]: DatetimeIndex(['2010-01-04', '2010-02-01', '2010-03-01', '2010-04-01', '2010-05-03', '2010-06-01', '2010-07-01', '2010-08-02', '2010-09-01', '2010-10-01', '2010-11-01', '2010-12-01', '2011-01-03', '2011-02-01', '2011-03-01', '2011-04-01', '2011-05-02', '2011-06-01', '2011-07-01', '2011-08-01', '2011-09-01', '2011-10-03', '2011-11-01', '2011-12-01'], dtype='datetime64[ns]', freq='CBMS')
BusinessHour
()
In [204]:
bh
Out[204]:
<BusinessHour: bh=09:00-17:00>
# 2014-08-01 is Friday
In [205]:
pd
.
Timestamp
(
"2014-08-01 10:00"
)
.
weekday
()
Out[205]:
4
In [206]:
pd
.
Timestamp
(
"2014-08-01 10:00"
)
+
bh
Out[206]:
Timestamp('2014-08-01 11:00:00')
# Below example is the same as: pd.Timestamp('2014-08-01 09:00') + bh
In [207]:
pd
.
Timestamp
(
"2014-08-01 08:00"
)
+
bh
Out[207]:
Timestamp('2014-08-01 10:00:00')
# If the results is on the end time, move to the next business day
In [208]:
pd
.
Timestamp
(
"2014-08-01 16:00"
)
+
bh
Out[208]:
Timestamp('2014-08-04 09:00:00')
# Remainings are added to the next day
In [209]:
pd
.
Timestamp
(
"2014-08-01 16:30"
)
+
bh
Out[209]:
Timestamp('2014-08-04 09:30:00')
# Adding 2 business hours
In [210]:
pd
.
Timestamp
(
"2014-08-01 10:00"
)
+
pd
.
offsets
.
BusinessHour
(
2
)
Out[210]:
Timestamp('2014-08-01 12:00:00')
# Subtracting 3 business hours
In [211]:
pd
.
Timestamp
(
"2014-08-01 10:00"
)
+
pd
.
offsets
.
BusinessHour
(
-
3
)
Out[211]:
Timestamp('2014-07-31 15:00:00')
You can also specify start and end time by keywords. The argument must
be a str with an hour:minute representation or a datetime.time
instance. Specifying seconds, microseconds and nanoseconds as business hour
results in ValueError.
Passing start time later than end represents midnight business hour.
In this case, business hour exceeds midnight and overlap to the next day.
Valid business hours are distinguished by whether it started from valid BusinessDay.
In [217]: bh=pd.offsets.BusinessHour(start="17:00",end="09:00")In [218]: bhOut[218]: <BusinessHour: bh=17:00-09:00>In [219]: pd.Timestamp("2014-08-01 17:00")+bhOut[219]: Timestamp('2014-08-01 18:00:00')In [220]: pd.Timestamp("2014-08-01 23:00")+bhOut[220]: Timestamp('2014-08-02 00:00:00')# Although 2014-08-02 is Saturday,# it is valid because it starts from 08-01 (Friday).In [221]: pd.Timestamp("2014-08-02 04:00")+bhOut[221]: Timestamp('2014-08-02 05:00:00')# Although 2014-08-04 is Monday,# it is out of business hours because it starts from 08-03 (Sunday).In [222]: pd.Timestamp("2014-08-04 04:00")+bhOut[222]: Timestamp('2014-08-04 18:00:00')
Applying BusinessHour.rollforward and rollback to out of business hours results in
the next business hour start or previous day’s end. Different from other offsets, BusinessHour.rollforward
may output different results from apply by definition.
This is because one day’s business hour end is equal to next day’s business hour start. For example,
under the default business hours (9:00 - 17:00), there is no gap (0 minutes) between 2014-08-0117:00 and
2014-08-0409:00.
# This adjusts a Timestamp to business hour edgeIn [223]: pd.offsets.BusinessHour().rollback(pd.Timestamp("2014-08-02 15:00"))Out[223]: Timestamp('2014-08-01 17:00:00')In [224]: pd.offsets.BusinessHour().rollforward(pd.Timestamp("2014-08-02 15:00"))Out[224]: Timestamp('2014-08-04 09:00:00')# It is the same as BusinessHour() + pd.Timestamp('2014-08-01 17:00').# And it is the same as BusinessHour() + pd.Timestamp('2014-08-04 09:00')In [225]: pd.offsets.BusinessHour()+pd.Timestamp("2014-08-02 15:00")Out[225]: Timestamp('2014-08-04 10:00:00')# BusinessDay results (for reference)In [226]: pd.offsets.BusinessHour().rollforward(pd.Timestamp("2014-08-02"))Out[226]: Timestamp('2014-08-04 09:00:00')# It is the same as BusinessDay() + pd.Timestamp('2014-08-01')# The result is the same as rollworward because BusinessDay never overlap.In [227]: pd.offsets.BusinessHour()+pd.Timestamp("2014-08-02")Out[227]: Timestamp('2014-08-04 10:00:00')
BusinessHour regards Saturday and Sunday as holidays. To use arbitrary
holidays, you can use CustomBusinessHour offset, as explained in the
following subsection.
.
CustomBusinessHour
(
calendar
=
USFederalHolidayCalendar
())
# Friday before MLK Day
In [230]:
dt
=
datetime
.
datetime
(
2014
,
1
,
17
,
15
)
In [231]:
dt
+
bhour_us
Out[231]:
Timestamp('2014-01-17 16:00:00')
# Tuesday after MLK Day (Monday is skipped because it's a holiday)
In [232]:
dt
+
bhour_us
*
2
Out[232]:
Timestamp('2014-01-21 09:00:00')
You can use keyword arguments supported by either BusinessHour and CustomBusinessDay.
In [233]: bhour_mon=pd.offsets.CustomBusinessHour(start="10:00",weekmask="Tue Wed Thu Fri")# Monday is skipped because it's a holiday, business hour starts from 10:00In [234]: dt+bhour_mon*2Out[234]: Timestamp('2014-01-21 10:00:00')
quarterly frequency, year ends in December. Same as ‘QE’
(B)Q(E)(S)-JAN
quarterly frequency, year ends in January
(B)Q(E)(S)-FEB
quarterly frequency, year ends in February
(B)Q(E)(S)-MAR
quarterly frequency, year ends in March
(B)Q(E)(S)-APR
quarterly frequency, year ends in April
(B)Q(E)(S)-MAY
quarterly frequency, year ends in May
(B)Q(E)(S)-JUN
quarterly frequency, year ends in June
(B)Q(E)(S)-JUL
quarterly frequency, year ends in July
(B)Q(E)(S)-AUG
quarterly frequency, year ends in August
(B)Q(E)(S)-SEP
quarterly frequency, year ends in September
(B)Q(E)(S)-OCT
quarterly frequency, year ends in October
(B)Q(E)(S)-NOV
quarterly frequency, year ends in November
(B)Y(E)(S)-DEC
annual frequency, anchored end of December. Same as ‘YE’
(B)Y(E)(S)-JAN
annual frequency, anchored end of January
(B)Y(E)(S)-FEB
annual frequency, anchored end of February
(B)Y(E)(S)-MAR
annual frequency, anchored end of March
(B)Y(E)(S)-APR
annual frequency, anchored end of April
(B)Y(E)(S)-MAY
annual frequency, anchored end of May
(B)Y(E)(S)-JUN
annual frequency, anchored end of June
(B)Y(E)(S)-JUL
annual frequency, anchored end of July
(B)Y(E)(S)-AUG
annual frequency, anchored end of August
(B)Y(E)(S)-SEP
annual frequency, anchored end of September
(B)Y(E)(S)-OCT
annual frequency, anchored end of October
(B)Y(E)(S)-NOV
annual frequency, anchored end of November
These can be used as arguments to date_range, bdate_range, constructors
for DatetimeIndex, as well as various other timeseries-related functions
in pandas.
MonthBegin
(
n
=
1
)
Out[243]:
Timestamp('2014-02-01 00:00:00')
In [244]:
pd
.
Timestamp
(
"2014-01-02"
)
+
pd
.
offsets
.
MonthEnd
(
n
=
1
)
Out[244]:
Timestamp('2014-01-31 00:00:00')
In [245]:
pd
.
Timestamp
(
"2014-01-02"
)
-
pd
.
offsets
.
MonthBegin
(
n
=
1
)
Out[245]:
Timestamp('2014-01-01 00:00:00')
In [246]:
pd
.
Timestamp
(
"2014-01-02"
)
-
pd
.
offsets
.
MonthEnd
(
n
=
1
)
Out[246]:
Timestamp('2013-12-31 00:00:00')
In [247]:
pd
.
Timestamp
(
"2014-01-02"
)
+
pd
.
offsets
.
MonthBegin
(
n
=
4
)
Out[247]:
Timestamp('2014-05-01 00:00:00')
In [248]:
pd
.
Timestamp
(
"2014-01-02"
)
-
pd
.
offsets
.
MonthBegin
(
n
=
4
)
Out[248]:
Timestamp('2013-10-01 00:00:00')
If the given date is on an anchor point, it is moved |n| points forwards
or backwards.
Using this calendar, creating an index or doing offset arithmetic skips weekends
and holidays (i.e., Memorial Day/July 4th). For example, the below defines
a custom business day offset using the ExampleCalendar. Like any other offset,
it can be used to create a DatetimeIndex or added to datetime
or Timestamp objects.
Every calendar class is accessible by name using the get_calendar function
which returns a holiday class instance. Any imported calendar class will
automatically be available by this function. Also, HolidayCalendarFactory
provides an easy interface to create calendars that are combinations of calendars
or calendars with additional rules.
In [274]: frompandas.tseries.holidayimportget_calendar,HolidayCalendarFactory,USLaborDayIn [275]: cal=get_calendar("ExampleCalendar")In [276]: cal.rulesOut[276]: [Holiday: Memorial Day (month=5, day=31, offset=<DateOffset: weekday=MO(-1)>), Holiday: July 4th (month=7, day=4, observance=<function nearest_workday at 0x7f8c4e5ab760>), Holiday: Columbus Day (month=10, day=1, offset=<DateOffset: weekday=MO(+2)>)]In [277]: new_cal=HolidayCalendarFactory("NewExampleCalendar",cal,USLaborDay)In [278]: new_cal.rulesOut[278]: [Holiday: Labor Day (month=9, day=1, offset=<DateOffset: weekday=MO(+1)>), Holiday: Memorial Day (month=5, day=31, offset=<DateOffset: weekday=MO(-1)>), Holiday: July 4th (month=7, day=4, observance=<function nearest_workday at 0x7f8c4e5ab760>), Holiday: Columbus Day (month=10, day=1, offset=<DateOffset: weekday=MO(+2)>)]
dtype: int64
In [284]:
ts
.
shift
(
5
,
freq
=
"BME"
)
Out[284]:
2012-05-31 0
2012-05-31 1
2012-05-31 2
dtype: int64
periods
=
3
,
freq
=
3
*
pd
.
offsets
.
BDay
())
In [286]:
ts
=
pd
.
Series
(
np
.
random
.
randn
(
3
),
index
=
dr
)
In [287]:
ts
Out[287]:
2010-01-01 1.494522
2010-01-06 -0.778425
2010-01-11 -0.253355
Freq: 3B, dtype: float64
In [288]:
ts
.
asfreq
(
pd
.
offsets
.
BDay
())
Out[288]:
2010-01-01 1.494522
2010-01-04 NaN
2010-01-05 NaN
2010-01-06 -0.778425
2010-01-07 NaN
2010-01-08 NaN
2010-01-11 -0.253355
Freq: B, dtype: float64
asfreq provides a further convenience so you can specify an interpolation
method for any gaps that may appear after the frequency conversion.
Notice how the value for Sunday got pulled back to the previous Friday.
To get the behavior where the value for Sunday is pushed to Monday, use
instead
Furthermore, you can also specify multiple aggregation functions for each column separately.
In [324]: r.agg({"A":["sum","std"],"B":["mean","std"]})Out[324]: A B sum std mean std2012-01-01 00:00:00 -6.088060 1.043263 -0.121514 1.0012942012-01-01 00:03:00 10.243678 1.058534 0.146731 1.0745972012-01-01 00:06:00 -10.590584 0.949264 0.047046 0.9873092012-01-01 00:09:00 11.362228 1.028096 -0.026158 0.9449532012-01-01 00:12:00 33.541257 0.884586 -0.003144 1.0950252012-01-01 00:15:00 -8.595393 1.035476 -0.016287 1.035312
If a DataFrame does not have a datetimelike index, but instead you want
to resample based on datetimelike column in the frame, it can passed to the
on keyword.
In [325]: df=pd.DataFrame( .....: {"date":pd.date_range("2015-01-01",freq="W",periods=5),"a":np.arange(5)}, .....: index=pd.MultiIndex.from_arrays( .....: [[1,2,3,4,5],pd.date_range("2015-01-01",freq="W",periods=5)], .....: names=["v","d"], .....: ), .....: ) .....: In [326]: dfOut[326]: date av d 1 2015-01-04 2015-01-04 02 2015-01-11 2015-01-11 13 2015-01-18 2015-01-18 24 2015-01-25 2015-01-25 35 2015-02-01 2015-02-01 4In [327]: df.resample("ME",on="date")[["a"]].sum()Out[327]: adate 2015-01-31 62015-02-28 4
Similarly, if you instead want to resample by a datetimelike
level of MultiIndex, its name or location can be passed to the
level keyword.
In [328]: df.resample("ME",level="d")[["a"]].sum()Out[328]: ad 2015-01-31 62015-02-28 4
Here we can see that, when using origin with its default value ('start_day'), the result after '2000-10-0200:00:00' are not identical depending on the start of time series:
If needed you can just adjust the bins with an offset Timedelta that would be added to the default origin.
Those two examples are equivalent for this time series:
The PeriodIndex constructor can also be used directly:
In [373]: pd.PeriodIndex(["2011-1","2011-2","2011-3"],freq="M")Out[373]: PeriodIndex(['2011-01', '2011-02', '2011-03'], dtype='period[M]')
Passing multiplied frequency outputs a sequence of Period which
has multiplied span.
In [374]: pd.period_range(start="2014-01",freq="3M",periods=4)Out[374]: PeriodIndex(['2014-01', '2014-04', '2014-07', '2014-10'], dtype='period[3M]')
If start or end are Period objects, they will be used as anchor
endpoints for a PeriodIndex with frequency matching that of the
PeriodIndex constructor.
The period dtype can be used in .astype(...). It allows one to change the
freq of a PeriodIndex like .asfreq() and convert a
DatetimeIndex to PeriodIndex like to_period():
In [402]: p.asfreq("M",how="start")Out[402]: Period('2011-01', 'M')In [403]: p.asfreq("M",how="end")Out[403]: Period('2011-12', 'M')
The shorthands ‘s’ and ‘e’ are provided for convenience:
In [404]: p.asfreq("M","s")Out[404]: Period('2011-01', 'M')In [405]: p.asfreq("M","e")Out[405]: Period('2011-12', 'M')
Converting to a “super-period” (e.g., annual frequency is a super-period of
quarterly frequency) automatically returns the super-period that includes the
input period:
In [406]: p=pd.Period("2011-12",freq="M")In [407]: p.asfreq("Y-NOV")Out[407]: Period('2012', 'Y-NOV')
Note that since we converted to an annual frequency that ends the year in
November, the monthly period of December 2011 is actually in the 2012 Y-NOV
period.
Period conversions with anchored frequencies are particularly useful for
working with various quarterly data common to economics, business, and other
fields. Many organizations define quarters relative to the month in which their
fiscal year starts and ends. Thus, first quarter of 2011 could start in 2010 or
a few months into 2011. Via anchored frequencies, pandas works for all quarterly
frequencies Q-JAN through Q-DEC.
This will fail as there are ambiguous times ('11/06/201101:00')
In [483]: rng_hourly.tz_localize('US/Eastern')---------------------------------------------------------------------------AmbiguousTimeErrorTraceback (most recent call last)
CellIn[483],line1----> 1rng_hourly.tz_localize('US/Eastern')File ~/work/pandas/pandas/pandas/core/indexes/datetimes.py:293, in DatetimeIndex.tz_localize(self, tz, ambiguous, nonexistent)286@doc(DatetimeArray.tz_localize)287deftz_localize(288self,(...)291nonexistent:TimeNonexistent="raise",292)->Self:--> 293arr=self._data.tz_localize(tz,ambiguous,nonexistent)294returntype(self)._simple_new(arr,name=self.name)File ~/work/pandas/pandas/pandas/core/arrays/_mixins.py:81, in ravel_compat.<locals>.method(self, *args, **kwargs)78@wraps(meth)79defmethod(self,*args,**kwargs):80ifself.ndim==1:---> 81returnmeth(self,*args,**kwargs)83flags=self._ndarray.flags84flat=self.ravel("K")File ~/work/pandas/pandas/pandas/core/arrays/datetimes.py:1090, in DatetimeArray.tz_localize(self, tz, ambiguous, nonexistent)1087tz=timezones.maybe_get_tz(tz)1088# Convert to UTC-> 1090new_dates=tzconversion.tz_localize_to_utc(1091self.asi8,1092tz,1093ambiguous=ambiguous,1094nonexistent=nonexistent,1095creso=self._creso,1096)1097new_dates_dt64=new_dates.view(f"M8[{self.unit}]")1098dtype=tz_to_dtype(tz,unit=self.unit)File ~/work/pandas/pandas/pandas/_libs/tslibs/tzconversion.pyx:371, in pandas._libs.tslibs.tzconversion.tz_localize_to_utc()AmbiguousTimeError: Cannot infer dst time from 2011-11-06 01:00:00, try using the 'ambiguous' argument
Handle these ambiguous times by specifying the following.
Time zone information can also be manipulated using the astype method.
This method can convert between different timezone-aware dtypes.
# convert to a new time zoneIn [499]: s_aware.astype("datetime64[ns, CET]")Out[499]: 0 2013-01-01 06:00:00+01:001 2013-01-02 06:00:00+01:002 2013-01-03 06:00:00+01:00dtype: datetime64[ns, CET]