### Navigation

- index
- modules |
- next |
- previous |
- pandas 0.14.1 documentation »

# Time Series / Date functionality

pandas has proven very successful as a tool for working with time series data, especially in the financial data analysis space. With the 0.8 release, we have further improved the time series API in pandas by leaps and bounds. Using the new NumPy `datetime64` dtype, we have 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.

In working with time series data, we will frequently seek to:

> - generate sequences of fixed-frequency dates and time spans
> - conform or convert time series to a particular frequency
> - compute “relative” dates based on various non-standard time increments (e.g. 5 business days before the last business day of the year), or “roll” dates forward or backward

pandas provides a relatively compact and self-contained set of tools for performing the above tasks.

Create a range of dates:

    # 72 hours starting with midnight Jan 1st, 2011
    In [1]: rng = date_range('1/1/2011', periods=72, freq='H')

    In [2]: rng[:5]
    Out[2]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2011-01-01 00:00:00, ..., 2011-01-01 04:00:00]
    Length: 5, Freq: H, Timezone: None

Index pandas objects with dates:

    In [3]: ts = Series(randn(len(rng)), index=rng)

    In [4]: ts.head()
    Out[4]:
    2011-01-01 00:00:00    0.469112
    2011-01-01 01:00:00   -0.282863
    2011-01-01 02:00:00   -1.509059
    2011-01-01 03:00:00   -1.135632
    2011-01-01 04:00:00    1.212112
    Freq: H, dtype: float64

Change frequency and fill gaps:

    # to 45 minute frequency and forward fill
    In [5]: converted = ts.asfreq('45Min', method='pad')

    In [6]: converted.head()
    Out[6]:
    2011-01-01 00:00:00    0.469112
    2011-01-01 00:45:00    0.469112
    2011-01-01 01:30:00   -0.282863
    2011-01-01 02:15:00   -1.509059
    2011-01-01 03:00:00   -1.135632
    Freq: 45T, dtype: float64

Resample:

    # Daily means
    In [7]: ts.resample('D', how='mean')
    Out[7]:
    2011-01-01   -0.319569
    2011-01-02   -0.337703
    2011-01-03    0.117258
    Freq: D, dtype: float64

## Time Stamps vs. Time Spans

Time-stamped data is the most basic type of timeseries data that associates values with points in time. For pandas objects it means using the points in time to create the index

    In [8]: dates = [datetime(2012, 5, 1), datetime(2012, 5, 2), datetime(2012, 5, 3)]

    In [9]: ts = Series(np.random.randn(3), dates)

    In [10]: type(ts.index)
    Out[10]: pandas.tseries.index.DatetimeIndex

    In [11]: ts
    Out[11]:
    2012-05-01   -0.410001
    2012-05-02   -0.078638
    2012-05-03    0.545952
    dtype: float64

However, in many cases it is more natural to associate things like change variables with a time span instead.

For example:

    In [12]: periods = PeriodIndex([Period('2012-01'), Period('2012-02'),
       ....:                        Period('2012-03')])
       ....:

    In [13]: ts = Series(np.random.randn(3), periods)

    In [14]: type(ts.index)
    Out[14]: pandas.tseries.period.PeriodIndex

    In [15]: ts
    Out[15]:
    2012-01   -1.219217
    2012-02   -1.226825
    2012-03    0.769804
    Freq: M, dtype: float64

Starting with 0.8, 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:

    In [16]: to_datetime(Series(['Jul 31, 2009', '2010-01-10', None]))
    Out[16]:
    0   2009-07-31
    1   2010-01-10
    2          NaT
    dtype: datetime64[ns]

    In [17]: to_datetime(['2005/11/23', '2010.12.31'])
    Out[17]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2005-11-23, 2010-12-31]
    Length: 2, Freq: None, Timezone: None

If you use dates which start with the day first (i.e. European style), you can pass the `dayfirst` flag:

    In [18]: to_datetime(['04-01-2012 10:00'], dayfirst=True)
    Out[18]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2012-01-04 10:00:00]
    Length: 1, Freq: None, Timezone: None

    In [19]: to_datetime(['14-01-2012', '01-14-2012'], dayfirst=True)
    Out[19]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2012-01-14, 2012-01-14]
    Length: 2, Freq: None, Timezone: None

Warning

You see in the above example that `dayfirst` isn’t strict, so if a date can’t be parsed with the day being first it will be parsed as if `dayfirst` were False.

Note

Specifying a `format` argument will potentially speed up the conversion considerably and on versions later then 0.13.0 explicitly specifying a format string of ‘%Y%m%d’ takes a faster path still.

### Invalid Data

Pass `coerce=True` to convert invalid data to `NaT` (not a time):

    In [20]: to_datetime(['2009-07-31', 'asd'])
    Out[20]: array(['2009-07-31', 'asd'], dtype=object)

    In [21]: to_datetime(['2009-07-31', 'asd'], coerce=True)
    Out[21]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2009-07-31, NaT]
    Length: 2, Freq: None, Timezone: None

Take care, `to_datetime` may not act as you expect on mixed data:

    In [22]: to_datetime([1, '1'])
    Out[22]: array([1, '1'], dtype=object)

### Epoch Timestamps

It’s also possible to convert integer or float epoch times. The default unit for these is nanoseconds (since these are how Timestamps are stored). However, often epochs are stored in another `unit` which can be specified:

Typical epoch stored units

    In [23]: to_datetime([1349720105, 1349806505, 1349892905,
       ....:              1349979305, 1350065705], unit='s')
       ....:
    Out[23]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2012-10-08 18:15:05, ..., 2012-10-12 18:15:05]
    Length: 5, Freq: None, Timezone: None

    In [24]: to_datetime([1349720105100, 1349720105200, 1349720105300,
       ....:              1349720105400, 1349720105500 ], unit='ms')
       ....:
    Out[24]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2012-10-08 18:15:05.100000, ..., 2012-10-08 18:15:05.500000]
    Length: 5, Freq: None, Timezone: None

These work, but the results may be unexpected.

    In [25]: to_datetime([1])
    Out[25]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [1970-01-01 00:00:00.000000001]
    Length: 1, Freq: None, Timezone: None

    In [26]: to_datetime([1, 3.14], unit='s')
    Out[26]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [1970-01-01 00:00:01, 1970-01-01 00:00:03.140000]
    Length: 2, Freq: None, Timezone: None

Note

Epoch times will be rounded to the nearest nanosecond.

## Generating Ranges of Timestamps

To generate an index with time stamps, you can use either the DatetimeIndex or Index constructor and pass in a list of datetime objects:

    In [27]: dates = [datetime(2012, 5, 1), datetime(2012, 5, 2), datetime(2012, 5, 3)]

    In [28]: index = DatetimeIndex(dates)

    In [29]: index # Note the frequency information
    Out[29]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2012-05-01, ..., 2012-05-03]
    Length: 3, Freq: None, Timezone: None

    In [30]: index = Index(dates)

    In [31]: index # Automatically converted to DatetimeIndex
    Out[31]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2012-05-01, ..., 2012-05-03]
    Length: 3, Freq: None, Timezone: None

Practically, 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 pandas functions `date_range` and `bdate_range` to create timestamp indexes.

    In [32]: index = date_range('2000-1-1', periods=1000, freq='M')

    In [33]: index
    Out[33]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2000-01-31, ..., 2083-04-30]
    Length: 1000, Freq: M, Timezone: None

    In [34]: index = bdate_range('2012-1-1', periods=250)

    In [35]: index
    Out[35]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2012-01-02, ..., 2012-12-14]
    Length: 250, Freq: B, Timezone: None

Convenience functions like `date_range` and `bdate_range` utilize a variety of frequency aliases. The default frequency for `date_range` is a calendar day while the default for `bdate_range` is a business day

    In [36]: start = datetime(2011, 1, 1)

    In [37]: end = datetime(2012, 1, 1)

    In [38]: rng = date_range(start, end)

    In [39]: rng
    Out[39]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2011-01-01, ..., 2012-01-01]
    Length: 366, Freq: D, Timezone: None

    In [40]: rng = bdate_range(start, end)

    In [41]: rng
    Out[41]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2011-01-03, ..., 2011-12-30]
    Length: 260, Freq: B, Timezone: None

`date_range` and `bdate_range` makes it easy to generate a range of dates using various combinations of parameters like `start`, `end`, `periods`, and `freq`:

    In [42]: date_range(start, end, freq='BM')
    Out[42]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2011-01-31, ..., 2011-12-30]
    Length: 12, Freq: BM, Timezone: None

    In [43]: date_range(start, end, freq='W')
    Out[43]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2011-01-02, ..., 2012-01-01]
    Length: 53, Freq: W-SUN, Timezone: None

    In [44]: bdate_range(end=end, periods=20)
    Out[44]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2011-12-05, ..., 2011-12-30]
    Length: 20, Freq: B, Timezone: None

    In [45]: bdate_range(start=start, periods=20)
    Out[45]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2011-01-03, ..., 2011-01-28]
    Length: 20, Freq: B, Timezone: None

The start and end dates are strictly inclusive. So it will not generate any dates outside of those dates if specified.

## DatetimeIndex

One of the main uses for `DatetimeIndex` is as an index for pandas objects. The `DatetimeIndex` class contains many timeseries 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` and `tshift` 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 has all the basic functionality of regular Index objects and a smorgasbord of advanced timeseries-specific methods for easy frequency processing.

See also

Reindexing methods

Note

While pandas does not force you to have a sorted date index, some of these methods may have unexpected or incorrect behavior if the dates are unsorted. So please be careful.

`DatetimeIndex` can be used like a regular index and offers all of its intelligent functionality like selection, slicing, etc.

    In [46]: rng = date_range(start, end, freq='BM')

    In [47]: ts = Series(randn(len(rng)), index=rng)

    In [48]: ts.index
    Out[48]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2011-01-31, ..., 2011-12-30]
    Length: 12, Freq: BM, Timezone: None

    In [49]: ts[:5].index
    Out[49]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2011-01-31, ..., 2011-05-31]
    Length: 5, Freq: BM, Timezone: None

    In [50]: ts[::2].index
    Out[50]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2011-01-31, ..., 2011-11-30]
    Length: 6, Freq: 2BM, Timezone: None

### DatetimeIndex Partial String Indexing

You can pass in dates and strings that parse to dates as indexing parameters:

    In [51]: ts['1/31/2011']
    Out[51]: -1.2812473076599529

    In [52]: ts[datetime(2011, 12, 25):]
    Out[52]:
    2011-12-30    0.687738
    Freq: BM, dtype: float64

    In [53]: ts['10/31/2011':'12/31/2011']
    Out[53]:
    2011-10-31    0.149748
    2011-11-30   -0.732339
    2011-12-30    0.687738
    Freq: BM, dtype: float64

To provide convenience for accessing longer time series, you can also pass in the year or year and month as strings:

    In [54]: ts['2011']
    Out[54]:
    2011-01-31   -1.281247
    2011-02-28   -0.727707
    2011-03-31   -0.121306
    2011-04-29   -0.097883
    2011-05-31    0.695775
    2011-06-30    0.341734
    2011-07-29    0.959726
    2011-08-31   -1.110336
    2011-09-30   -0.619976
    2011-10-31    0.149748
    2011-11-30   -0.732339
    2011-12-30    0.687738
    Freq: BM, dtype: float64

    In [55]: ts['2011-6']
    Out[55]:
    2011-06-30    0.341734
    Freq: BM, dtype: float64

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. Here’s an example:

    In [56]: dft = DataFrame(randn(100000,1),columns=['A'],index=date_range('20130101',periods=100000,freq='T'))

    In [57]: dft
    Out[57]:
                                A
    2013-01-01 00:00:00  0.176444
    2013-01-01 00:01:00  0.403310
    2013-01-01 00:02:00 -0.154951
    2013-01-01 00:03:00  0.301624
    2013-01-01 00:04:00 -2.179861
    2013-01-01 00:05:00 -1.369849
    2013-01-01 00:06:00 -0.954208
    ...                       ...
    2013-03-11 10:33:00 -0.293083
    2013-03-11 10:34:00 -0.059881
    2013-03-11 10:35:00  1.252450
    2013-03-11 10:36:00  0.046611
    2013-03-11 10:37:00  0.059478
    2013-03-11 10:38:00 -0.286539
    2013-03-11 10:39:00  0.841669

    [100000 rows x 1 columns]

    In [58]: dft['2013']
    Out[58]:
                                A
    2013-01-01 00:00:00  0.176444
    2013-01-01 00:01:00  0.403310
    2013-01-01 00:02:00 -0.154951
    2013-01-01 00:03:00  0.301624
    2013-01-01 00:04:00 -2.179861
    2013-01-01 00:05:00 -1.369849
    2013-01-01 00:06:00 -0.954208
    ...                       ...
    2013-03-11 10:33:00 -0.293083
    2013-03-11 10:34:00 -0.059881
    2013-03-11 10:35:00  1.252450
    2013-03-11 10:36:00  0.046611
    2013-03-11 10:37:00  0.059478
    2013-03-11 10:38:00 -0.286539
    2013-03-11 10:39:00  0.841669

    [100000 rows x 1 columns]

This starts on the very first time in the month, and includes the last date & time for the month

    In [59]: dft['2013-1':'2013-2']
    Out[59]:
                                A
    2013-01-01 00:00:00  0.176444
    2013-01-01 00:01:00  0.403310
    2013-01-01 00:02:00 -0.154951
    2013-01-01 00:03:00  0.301624
    2013-01-01 00:04:00 -2.179861
    2013-01-01 00:05:00 -1.369849
    2013-01-01 00:06:00 -0.954208
    ...                       ...
    2013-02-28 23:53:00  0.103114
    2013-02-28 23:54:00 -1.303422
    2013-02-28 23:55:00  0.451943
    2013-02-28 23:56:00  0.220534
    2013-02-28 23:57:00 -1.624220
    2013-02-28 23:58:00  0.093915
    2013-02-28 23:59:00 -1.087454

    [84960 rows x 1 columns]

This specifies a stop time that includes all of the times on the last day

    In [60]: dft['2013-1':'2013-2-28']
    Out[60]:
                                A
    2013-01-01 00:00:00  0.176444
    2013-01-01 00:01:00  0.403310
    2013-01-01 00:02:00 -0.154951
    2013-01-01 00:03:00  0.301624
    2013-01-01 00:04:00 -2.179861
    2013-01-01 00:05:00 -1.369849
    2013-01-01 00:06:00 -0.954208
    ...                       ...
    2013-02-28 23:53:00  0.103114
    2013-02-28 23:54:00 -1.303422
    2013-02-28 23:55:00  0.451943
    2013-02-28 23:56:00  0.220534
    2013-02-28 23:57:00 -1.624220
    2013-02-28 23:58:00  0.093915
    2013-02-28 23:59:00 -1.087454

    [84960 rows x 1 columns]

This specifies an exact stop time (and is not the same as the above)

    In [61]: dft['2013-1':'2013-2-28 00:00:00']
    Out[61]:
                                A
    2013-01-01 00:00:00  0.176444
    2013-01-01 00:01:00  0.403310
    2013-01-01 00:02:00 -0.154951
    2013-01-01 00:03:00  0.301624
    2013-01-01 00:04:00 -2.179861
    2013-01-01 00:05:00 -1.369849
    2013-01-01 00:06:00 -0.954208
    ...                       ...
    2013-02-27 23:54:00  0.897051
    2013-02-27 23:55:00 -0.309230
    2013-02-27 23:56:00  1.944713
    2013-02-27 23:57:00  0.369265
    2013-02-27 23:58:00  0.053071
    2013-02-27 23:59:00 -0.019734
    2013-02-28 00:00:00  1.388189

    [83521 rows x 1 columns]

We are stopping on the included end-point as its part of the index

    In [62]: dft['2013-1-15':'2013-1-15 12:30:00']
    Out[62]:
                                A
    2013-01-15 00:00:00  0.501288
    2013-01-15 00:01:00 -0.605198
    2013-01-15 00:02:00  0.215146
    2013-01-15 00:03:00  0.924732
    2013-01-15 00:04:00 -2.228519
    2013-01-15 00:05:00  1.517331
    2013-01-15 00:06:00 -1.188774
    ...                       ...
    2013-01-15 12:24:00  1.358314
    2013-01-15 12:25:00 -0.737727
    2013-01-15 12:26:00  1.838323
    2013-01-15 12:27:00 -0.774090
    2013-01-15 12:28:00  0.622261
    2013-01-15 12:29:00 -0.631649
    2013-01-15 12:30:00  0.193284

    [751 rows x 1 columns]

Warning

The following selection will raise a `KeyError`; otherwise this selection methodology would be inconsistent with other selection methods in pandas (as this is not a slice, nor does it resolve to one)

    dft['2013-1-15 12:30:00']

To select a single row, use `.loc`

    In [63]: dft.loc['2013-1-15 12:30:00']
    Out[63]:
    A    0.193284
    Name: 2013-01-15 12:30:00, dtype: float64

### Datetime Indexing

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 frequency of the index. In contrast, indexing with datetime objects is exact, because the objects have exact meaning. These also follow the sematics of including both endpoints.

These `datetime` objects are specific `hours, minutes,` and `seconds` even though they were not explicity specified (they are `0`).

    In [64]: dft[datetime(2013, 1, 1):datetime(2013,2,28)]
    Out[64]:
                                A
    2013-01-01 00:00:00  0.176444
    2013-01-01 00:01:00  0.403310
    2013-01-01 00:02:00 -0.154951
    2013-01-01 00:03:00  0.301624
    2013-01-01 00:04:00 -2.179861
    2013-01-01 00:05:00 -1.369849
    2013-01-01 00:06:00 -0.954208
    ...                       ...
    2013-02-27 23:54:00  0.897051
    2013-02-27 23:55:00 -0.309230
    2013-02-27 23:56:00  1.944713
    2013-02-27 23:57:00  0.369265
    2013-02-27 23:58:00  0.053071
    2013-02-27 23:59:00 -0.019734
    2013-02-28 00:00:00  1.388189

    [83521 rows x 1 columns]

With no defaults.

    In [65]: dft[datetime(2013, 1, 1, 10, 12, 0):datetime(2013, 2, 28, 10, 12, 0)]
    Out[65]:
                                A
    2013-01-01 10:12:00 -0.246733
    2013-01-01 10:13:00 -1.429225
    2013-01-01 10:14:00 -1.265339
    2013-01-01 10:15:00  0.710986
    2013-01-01 10:16:00 -0.818200
    2013-01-01 10:17:00  0.543542
    2013-01-01 10:18:00  1.577713
    ...                       ...
    2013-02-28 10:06:00  0.311249
    2013-02-28 10:07:00  2.366080
    2013-02-28 10:08:00 -0.490372
    2013-02-28 10:09:00  0.373340
    2013-02-28 10:10:00  0.638442
    2013-02-28 10:11:00  1.330135
    2013-02-28 10:12:00 -0.945450

    [83521 rows x 1 columns]

### Truncating & Fancy Indexing

A `truncate` convenience function is provided that is equivalent to slicing:

    In [66]: ts.truncate(before='10/31/2011', after='12/31/2011')
    Out[66]:
    2011-10-31    0.149748
    2011-11-30   -0.732339
    2011-12-30    0.687738
    Freq: BM, dtype: float64

Even complicated fancy indexing that breaks the DatetimeIndex’s frequency regularity will result in a `DatetimeIndex` (but frequency is lost):

    In [67]: ts[[0, 2, 6]].index
    Out[67]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2011-01-31, ..., 2011-07-29]
    Length: 3, Freq: None, Timezone: None

### 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
time | Returns datetime.time
dayofyear | The ordinal day of year
weekofyear | The week ordinal of the year
week | The week ordinal of the year
dayofweek | The day of the week with Monday=0, Sunday=6
weekday | The day of the week with Monday=0, Sunday=6
quarter | Quarter of the date: Jan=Mar = 1, Apr-Jun = 2, etc.
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)

## DateOffset objects

In the preceding examples, we created DatetimeIndex objects at various frequencies by passing in frequency strings like ‘M’, ‘W’, and ‘BM to the `freq` keyword. Under the hood, these frequency strings are being translated into an instance of pandas `DateOffset`, which represents a regular frequency increment. Specific offset logic like “month”, “business day”, or “one hour” is represented in its various subclasses.

Class name | Description
--- | ---
DateOffset | Generic offset class, defaults to 1 calendar day
BDay | business day (weekday)
CDay | custom business day (experimental)
Week | one week, optionally anchored on a day of the week
WeekOfMonth | the x-th day of the y-th week of each month
LastWeekOfMonth | the x-th day of the last week of each month
MonthEnd | calendar month end
MonthBegin | calendar month begin
BMonthEnd | business month end
BMonthBegin | business month begin
CBMonthEnd | custom business month end
CBMonthBegin | custom business month begin
QuarterEnd | calendar quarter end
QuarterBegin | calendar quarter begin
BQuarterEnd | business quarter end
BQuarterBegin | business quarter begin
FY5253Quarter | retail (aka 52-53 week) quarter
YearEnd | calendar year end
YearBegin | calendar year begin
BYearEnd | business year end
BYearBegin | business year begin
FY5253 | retail (aka 52-53 week) year
Hour | one hour
Minute | one minute
Second | one second
Milli | one millisecond
Micro | one microsecond

The basic `DateOffset` takes the same arguments as `dateutil.relativedelta`, which works like:

    In [68]: d = datetime(2008, 8, 18, 9, 0)

    In [69]: d + relativedelta(months=4, days=5)
    Out[69]: datetime.datetime(2008, 12, 23, 9, 0)

We could have done the same thing with `DateOffset`:

    In [70]: from pandas.tseries.offsets import *

    In [71]: d + DateOffset(months=4, days=5)
    Out[71]: Timestamp('2008-12-23 09:00:00')

The key features of a `DateOffset` object are:

> - it can be added / subtracted to/from a datetime object to obtain a shifted date
> - it can be multiplied by an integer (positive or negative) so that the increment will be applied multiple times
> - it has `rollforward` and `rollback` methods for moving a date forward or backward to the next or previous “offset date”

Subclasses of `DateOffset` define the `apply` function which dictates custom date increment logic, such as adding business days:

    class BDay(DateOffset):
        """DateOffset increments between business days"""
        def apply(self, other):
            ...

    In [72]: d - 5 * BDay()
    Out[72]: Timestamp('2008-08-11 09:00:00')

    In [73]: d + BMonthEnd()
    Out[73]: Timestamp('2008-08-29 09:00:00')

The `rollforward` and `rollback` methods do exactly what you would expect:

    In [74]: d
    Out[74]: datetime.datetime(2008, 8, 18, 9, 0)

    In [75]: offset = BMonthEnd()

    In [76]: offset.rollforward(d)
    Out[76]: Timestamp('2008-08-29 09:00:00')

    In [77]: offset.rollback(d)
    Out[77]: Timestamp('2008-07-31 09:00:00')

It’s definitely worth exploring the `pandas.tseries.offsets` module and the various docstrings for the classes.

These operations (`apply`, `rollforward` and `rollback`) preserves time (hour, minute, etc) information by default. To reset time, use `normalize=True` keyword when create offset instance. If `normalize=True`, result is normalized after the function is applied.

>     In [78]: day = Day()

>     In [79]: day.apply(Timestamp('2014-01-01 09:00'))
>     Out[79]: Timestamp('2014-01-02 09:00:00')

>     In [80]: day = Day(normalize=True)

>     In [81]: day.apply(Timestamp('2014-01-01 09:00'))
>     Out[81]: Timestamp('2014-01-02 00:00:00')

>     In [82]: hour = Hour()

>     In [83]: hour.apply(Timestamp('2014-01-01 22:00'))
>     Out[83]: Timestamp('2014-01-01 23:00:00')

>     In [84]: hour = Hour(normalize=True)

>     In [85]: hour.apply(Timestamp('2014-01-01 22:00'))
>     Out[85]: Timestamp('2014-01-01 00:00:00')

>     In [86]: hour.apply(Timestamp('2014-01-01 23:00'))
>     Out[86]: Timestamp('2014-01-02 00:00:00')

### Parametric offsets

Some of the offsets can be “parameterized” when created to result in different behavior. 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:

    In [87]: d
    Out[87]: datetime.datetime(2008, 8, 18, 9, 0)

    In [88]: d + Week()
    Out[88]: Timestamp('2008-08-25 09:00:00')

    In [89]: d + Week(weekday=4)
    Out[89]: Timestamp('2008-08-22 09:00:00')

    In [90]: (d + Week(weekday=4)).weekday()
    Out[90]: 4

    In [91]: d - Week()
    Out[91]: Timestamp('2008-08-11 09:00:00')

`normalize` option will be effective for addition and subtraction.

    In [92]: d + Week(normalize=True)
    Out[92]: Timestamp('2008-08-25 00:00:00')

    In [93]: d - Week(normalize=True)
    Out[93]: Timestamp('2008-08-11 00:00:00')

Another example is parameterizing `YearEnd` with the specific ending month:

    In [94]: d + YearEnd()
    Out[94]: Timestamp('2008-12-31 09:00:00')

    In [95]: d + YearEnd(month=6)
    Out[95]: Timestamp('2009-06-30 09:00:00')

### Custom Business Days (Experimental)

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.

    In [96]: from pandas.tseries.offsets import CustomBusinessDay

    # As an interesting example, let's look at Egypt where
    # a Friday-Saturday weekend is observed.
    In [97]: weekmask_egypt = 'Sun Mon Tue Wed Thu'

    # They also observe International Workers' Day so let's
    # add that for a couple of years
    In [98]: holidays = ['2012-05-01', datetime(2013, 5, 1), np.datetime64('2014-05-01')]

    In [99]: bday_egypt = CustomBusinessDay(holidays=holidays, weekmask=weekmask_egypt)

    In [100]: dt = datetime(2013, 4, 30)

    In [101]: dt + 2 * bday_egypt
    Out[101]: Timestamp('2013-05-05 00:00:00')

    In [102]: dts = date_range(dt, periods=5, freq=bday_egypt)

    In [103]: Series(dts.weekday, dts).map(Series('Mon Tue Wed Thu Fri Sat Sun'.split()))
    Out[103]:
    2013-04-30    Tue
    2013-05-02    Thu
    2013-05-05    Sun
    2013-05-06    Mon
    2013-05-07    Tue
    Freq: C, dtype: object

As of v0.14 holiday calendars can be used to provide the list of holidays. See the holiday calendar section for more information.

    In [104]: from pandas.tseries.holiday import USFederalHolidayCalendar

    In [105]: bday_us = CustomBusinessDay(calendar=USFederalHolidayCalendar())

    # Friday before MLK Day
    In [106]: dt = datetime(2014, 1, 17)

    # Tuesday after MLK Day (Monday is skipped because it's a holiday)
    In [107]: dt + bday_us
    Out[107]: Timestamp('2014-01-21 00:00:00')

Monthly offsets that respect a certain holiday calendar can be defined in the usual way.

    In [108]: from pandas.tseries.offsets import CustomBusinessMonthBegin

    In [109]: bmth_us = CustomBusinessMonthBegin(calendar=USFederalHolidayCalendar())

    # Skip new years
    In [110]: dt = datetime(2013, 12, 17)

    In [111]: dt + bmth_us
    Out[111]: Timestamp('2014-01-02 00:00:00')

    # Define date index with custom offset
    In [112]: from pandas import DatetimeIndex

    In [113]: DatetimeIndex(start='20100101',end='20120101',freq=bmth_us)
    Out[113]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2010-01-04, ..., 2011-12-01]
    Length: 24, Freq: CBMS, Timezone: None

Note

The frequency string ‘C’ is used to indicate that a CustomBusinessDay DateOffset is used, it is important to note that since CustomBusinessDay is a parameterised type, instances of CustomBusinessDay may differ and this is not detectable from the ‘C’ frequency string. The user therefore needs to ensure that the ‘C’ frequency string is used consistently within the user’s application.

Note

This uses the `numpy.busdaycalendar` API introduced in Numpy 1.7 and therefore requires Numpy 1.7.0 or newer.

Warning

There are known problems with the timezone handling in Numpy 1.7 and users should therefore use this experimental(!) feature with caution and at their own risk.

To the extent that the `datetime64` and `busdaycalendar` APIs in Numpy have to change to fix the timezone issues, the behaviour of the `CustomBusinessDay` class may have to change in future versions.

### Offset Aliases

A number of string aliases are given to useful common time series frequencies. We will refer to these aliases as offset aliases (referred to as time rules prior to v0.8.0).

Alias | Description
--- | ---
B | business day frequency
C | custom business day frequency (experimental)
D | calendar day frequency
W | weekly frequency
M | month end frequency
BM | business month end frequency
CBM | custom business month end frequency
MS | month start frequency
BMS | business month start frequency
CBMS | custom business month start frequency
Q | quarter end frequency
BQ | business quarter endfrequency
QS | quarter start frequency
BQS | business quarter start frequency
A | year end frequency
BA | business year end frequency
AS | year start frequency
BAS | business year start frequency
H | hourly frequency
T | minutely frequency
S | secondly frequency
L | milliseonds
U | microseconds

### Combining Aliases

As we have seen previously, the alias and the offset instance are fungible in most functions:

    In [114]: date_range(start, periods=5, freq='B')
    Out[114]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2011-01-03, ..., 2011-01-07]
    Length: 5, Freq: B, Timezone: None

    In [115]: date_range(start, periods=5, freq=BDay())
    Out[115]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2011-01-03, ..., 2011-01-07]
    Length: 5, Freq: B, Timezone: None

You can combine together day and intraday offsets:

    In [116]: date_range(start, periods=10, freq='2h20min')
    Out[116]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2011-01-01 00:00:00, ..., 2011-01-01 21:00:00]
    Length: 10, Freq: 140T, Timezone: None

    In [117]: date_range(start, periods=10, freq='1D10U')
    Out[117]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2011-01-01 00:00:00, ..., 2011-01-10 00:00:00.000090]
    Length: 10, Freq: 86400000010U, Timezone: None

### Anchored Offsets

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)
W-WED | weekly frequency (wednesdays)
W-THU | weekly frequency (thursdays)
W-FRI | weekly frequency (fridays)
W-SAT | weekly frequency (saturdays)
(B)Q(S)-DEC | quarterly frequency, year ends in December. Same as ‘Q’
(B)Q(S)-JAN | quarterly frequency, year ends in January
(B)Q(S)-FEB | quarterly frequency, year ends in February
(B)Q(S)-MAR | quarterly frequency, year ends in March
(B)Q(S)-APR | quarterly frequency, year ends in April
(B)Q(S)-MAY | quarterly frequency, year ends in May
(B)Q(S)-JUN | quarterly frequency, year ends in June
(B)Q(S)-JUL | quarterly frequency, year ends in July
(B)Q(S)-AUG | quarterly frequency, year ends in August
(B)Q(S)-SEP | quarterly frequency, year ends in September
(B)Q(S)-OCT | quarterly frequency, year ends in October
(B)Q(S)-NOV | quarterly frequency, year ends in November
(B)A(S)-DEC | annual frequency, anchored end of December. Same as ‘A’
(B)A(S)-JAN | annual frequency, anchored end of January
(B)A(S)-FEB | annual frequency, anchored end of February
(B)A(S)-MAR | annual frequency, anchored end of March
(B)A(S)-APR | annual frequency, anchored end of April
(B)A(S)-MAY | annual frequency, anchored end of May
(B)A(S)-JUN | annual frequency, anchored end of June
(B)A(S)-JUL | annual frequency, anchored end of July
(B)A(S)-AUG | annual frequency, anchored end of August
(B)A(S)-SEP | annual frequency, anchored end of September
(B)A(S)-OCT | annual frequency, anchored end of October
(B)A(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.

### Legacy Aliases

Note that prior to v0.8.0, time rules had a slightly different look. pandas will continue to support the legacy time rules for the time being but it is strongly recommended that you switch to using the new offset aliases.

Legacy Time Rule | Offset Alias
--- | ---
WEEKDAY | B
EOM | BM
W@MON | W-MON
W@TUE | W-TUE
W@WED | W-WED
W@THU | W-THU
W@FRI | W-FRI
W@SAT | W-SAT
W@SUN | W-SUN
Q@JAN | BQ-JAN
Q@FEB | BQ-FEB
Q@MAR | BQ-MAR
A@JAN | BA-JAN
A@FEB | BA-FEB
A@MAR | BA-MAR
A@APR | BA-APR
A@MAY | BA-MAY
A@JUN | BA-JUN
A@JUL | BA-JUL
A@AUG | BA-AUG
A@SEP | BA-SEP
A@OCT | BA-OCT
A@NOV | BA-NOV
A@DEC | BA-DEC
min | T
ms | L
us | U

As you can see, legacy quarterly and annual frequencies are business quarter and business year ends. Please also note the legacy time rule for milliseconds `ms` versus the new offset alias for month start `MS`. This means that offset alias parsing is case sensitive.

### 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. Further, `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:

Rule | Description
--- | ---
nearest_workday | move Saturday to Friday and Sunday to Monday
sunday_to_monday | move Sunday to following Monday
next_monday_or_tuesday | move Saturday to Monday and Sunday/Monday to Tuesday
previous_friday | move Saturday and Sunday to previous Friday”
next_monday | move Saturday and Sunday to following Monday

An example of how holidays and holiday calendars are defined:

    In [118]: from pandas.tseries.holiday import Holiday, USMemorialDay,\
       .....:     AbstractHolidayCalendar, nearest_workday, MO
       .....:

    In [119]: class ExampleCalendar(AbstractHolidayCalendar):
       .....:     rules = [
       .....:         USMemorialDay,
       .....:         Holiday('July 4th', month=7, day=4, observance=nearest_workday),
       .....:         Holiday('Columbus Day', month=10, day=1,
       .....:             offset=DateOffset(weekday=MO(2))), #same as 2*Week(weekday=2)
       .....:         ]
       .....:

    In [120]: cal = ExampleCalendar()

    In [121]: cal.holidays(datetime(2012, 1, 1), datetime(2012, 12, 31))
    Out[121]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2012-05-28, ..., 2012-10-08]
    Length: 3, Freq: None, Timezone: None

Using this calendar, creating an index or doing offset arithmetic skips weekends and holidays (i.e., Memorial Day/July 4th).

    In [122]: DatetimeIndex(start='7/1/2012', end='7/10/2012',
       .....:     freq=CDay(calendar=cal)).to_pydatetime()
       .....:
    Out[122]:
    array([datetime.datetime(2012, 7, 2, 0, 0),
           datetime.datetime(2012, 7, 3, 0, 0),
           datetime.datetime(2012, 7, 5, 0, 0),
           datetime.datetime(2012, 7, 6, 0, 0),
           datetime.datetime(2012, 7, 9, 0, 0),
           datetime.datetime(2012, 7, 10, 0, 0)], dtype=object)

    In [123]: offset = CustomBusinessDay(calendar=cal)

    In [124]: datetime(2012, 5, 25) + offset
    Out[124]: Timestamp('2012-05-29 00:00:00')

    In [125]: datetime(2012, 7, 3) + offset
    Out[125]: Timestamp('2012-07-05 00:00:00')

    In [126]: datetime(2012, 7, 3) + 2 * offset
    Out[126]: Timestamp('2012-07-06 00:00:00')

    In [127]: datetime(2012, 7, 6) + offset
    Out[127]: Timestamp('2012-07-09 00:00:00')

Ranges are defined by the `start_date` and `end_date` class attributes of `AbstractHolidayCalendar`. The defaults are below.

    In [128]: AbstractHolidayCalendar.start_date
    Out[128]: Timestamp('1970-01-01 00:00:00')

    In [129]: AbstractHolidayCalendar.end_date
    Out[129]: Timestamp('2030-12-31 00:00:00')

These dates can be overwritten by setting the attributes as datetime/Timestamp/string.

    In [130]: AbstractHolidayCalendar.start_date = datetime(2012, 1, 1)

    In [131]: AbstractHolidayCalendar.end_date = datetime(2012, 12, 31)

    In [132]: cal.holidays()
    Out[132]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2012-05-28, ..., 2012-10-08]
    Length: 3, Freq: None, Timezone: None

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 [133]: from pandas.tseries.holiday import get_calendar, HolidayCalendarFactory,\
       .....:     USLaborDay
       .....:

    In [134]: cal = get_calendar('ExampleCalendar')

    In [135]: cal.rules
    Out[135]:
    [Holiday: MemorialDay (month=5, day=24, offset=<DateOffset: kwds={'weekday': MO(+1)}>),
     Holiday: July 4th (month=7, day=4, observance=<function nearest_workday at 0xa83966f4>),
     Holiday: Columbus Day (month=10, day=1, offset=<DateOffset: kwds={'weekday': MO(+2)}>)]

    In [136]: new_cal = HolidayCalendarFactory('NewExampleCalendar', cal, USLaborDay)

    In [137]: new_cal.rules
    Out[137]:
    [Holiday: Labor Day (month=9, day=1, offset=<DateOffset: kwds={'weekday': MO(+1)}>),
     Holiday: Columbus Day (month=10, day=1, offset=<DateOffset: kwds={'weekday': MO(+2)}>),
     Holiday: July 4th (month=7, day=4, observance=<function nearest_workday at 0xa83966f4>),
     Holiday: MemorialDay (month=5, day=24, offset=<DateOffset: kwds={'weekday': MO(+1)}>)]

## Time series-related instance methods

### Shifting / lagging

One may want to shift or lag the values in a TimeSeries back and forward in time. The method for this is `shift`, which is available on all of the pandas objects. In DataFrame, `shift` will currently only shift along the `index` and in Panel along the `major_axis`.

    In [138]: ts = ts[:5]

    In [139]: ts.shift(1)
    Out[139]:
    2011-01-31         NaN
    2011-02-28   -1.281247
    2011-03-31   -0.727707
    2011-04-29   -0.121306
    2011-05-31   -0.097883
    Freq: BM, dtype: float64

The shift method accepts an `freq` argument which can accept a `DateOffset` class or other `timedelta`-like object or also a offset alias:

    In [140]: ts.shift(5, freq=datetools.bday)
    Out[140]:
    2011-02-07   -1.281247
    2011-03-07   -0.727707
    2011-04-07   -0.121306
    2011-05-06   -0.097883
    2011-06-07    0.695775
    dtype: float64

    In [141]: ts.shift(5, freq='BM')
    Out[141]:
    2011-06-30   -1.281247
    2011-07-29   -0.727707
    2011-08-31   -0.121306
    2011-09-30   -0.097883
    2011-10-31    0.695775
    Freq: BM, dtype: float64

Rather than changing the alignment of the data and the index, `DataFrame` and `TimeSeries` objects also have a `tshift` convenience method that changes all the dates in the index by a specified number of offsets:

    In [142]: ts.tshift(5, freq='D')
    Out[142]:
    2011-02-05   -1.281247
    2011-03-05   -0.727707
    2011-04-05   -0.121306
    2011-05-04   -0.097883
    2011-06-05    0.695775
    dtype: float64

Note that with `tshift`, 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` function. For a `DatetimeIndex`, this is basically just a thin, but convenient wrapper around `reindex` which generates a `date_range` and calls `reindex`.

    In [143]: dr = date_range('1/1/2010', periods=3, freq=3 * datetools.bday)

    In [144]: ts = Series(randn(3), index=dr)

    In [145]: ts
    Out[145]:
    2010-01-01   -0.659574
    2010-01-06    1.494522
    2010-01-11   -0.778425
    Freq: 3B, dtype: float64

    In [146]: ts.asfreq(BDay())
    Out[146]:
    2010-01-01   -0.659574
    2010-01-04         NaN
    2010-01-05         NaN
    2010-01-06    1.494522
    2010-01-07         NaN
    2010-01-08         NaN
    2010-01-11   -0.778425
    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

    In [147]: ts.asfreq(BDay(), method='pad')
    Out[147]:
    2010-01-01   -0.659574
    2010-01-04   -0.659574
    2010-01-05   -0.659574
    2010-01-06    1.494522
    2010-01-07    1.494522
    2010-01-08    1.494522
    2010-01-11   -0.778425
    Freq: B, dtype: float64

### Filling forward / backward

Related to `asfreq` and `reindex` is the `fillna` function documented in the missing data section.

### Converting to Python datetimes

`DatetimeIndex` can be converted to an array of Python native datetime.datetime objects using the `to_pydatetime` method.

## Up- and downsampling

With 0.8, pandas introduces 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.

See some cookbook examples for some advanced strategies

    In [148]: rng = date_range('1/1/2012', periods=100, freq='S')

    In [149]: ts = Series(randint(0, 500, len(rng)), index=rng)

    In [150]: ts.resample('5Min', how='sum')
    Out[150]:
    2012-01-01    25103
    Freq: 5T, dtype: int32

The `resample` function is very flexible and allows you to specify many different parameters to control the frequency conversion and resampling operation.

The `how` parameter can be a function name or numpy array function that takes an array and produces aggregated values:

    In [151]: ts.resample('5Min') # default is mean
    Out[151]:
    2012-01-01    251.03
    Freq: 5T, dtype: float64

    In [152]: ts.resample('5Min', how='ohlc')
    Out[152]:
                open  high  low  close
    2012-01-01   308   460    9    205

    In [153]: ts.resample('5Min', how=np.max)
    Out[153]:
    2012-01-01    460
    Freq: 5T, dtype: int32

Any function available via dispatching can be given to the `how` parameter by name, including `sum`, `mean`, `std`, `sem`, `max`, `min`, `median`, `first`, `last`, `ohlc`.

For downsampling, `closed` can be set to ‘left’ or ‘right’ to specify which end of the interval is closed:

    In [154]: ts.resample('5Min', closed='right')
    Out[154]:
    2011-12-31 23:55:00    308.000000
    2012-01-01 00:00:00    250.454545
    Freq: 5T, dtype: float64

    In [155]: ts.resample('5Min', closed='left')
    Out[155]:
    2012-01-01    251.03
    Freq: 5T, dtype: float64

For upsampling, the `fill_method` and `limit` parameters can be specified to interpolate over the gaps that are created:

    # from secondly to every 250 milliseconds
    In [156]: ts[:2].resample('250L')
    Out[156]:
    2012-01-01 00:00:00           308
    2012-01-01 00:00:00.250000    NaN
    2012-01-01 00:00:00.500000    NaN
    2012-01-01 00:00:00.750000    NaN
    2012-01-01 00:00:01           204
    Freq: 250L, dtype: float64

    In [157]: ts[:2].resample('250L', fill_method='pad')
    Out[157]:
    2012-01-01 00:00:00           308
    2012-01-01 00:00:00.250000    308
    2012-01-01 00:00:00.500000    308
    2012-01-01 00:00:00.750000    308
    2012-01-01 00:00:01           204
    Freq: 250L, dtype: int32

    In [158]: ts[:2].resample('250L', fill_method='pad', limit=2)
    Out[158]:
    2012-01-01 00:00:00           308
    2012-01-01 00:00:00.250000    308
    2012-01-01 00:00:00.500000    308
    2012-01-01 00:00:00.750000    NaN
    2012-01-01 00:00:01           204
    Freq: 250L, dtype: float64

Parameters like `label` and `loffset` are used to manipulate the resulting labels. `label` specifies whether the result is labeled with the beginning or the end of the interval. `loffset` performs a time adjustment on the output labels.

    In [159]: ts.resample('5Min') # by default label='right'
    Out[159]:
    2012-01-01    251.03
    Freq: 5T, dtype: float64

    In [160]: ts.resample('5Min', label='left')
    Out[160]:
    2012-01-01    251.03
    Freq: 5T, dtype: float64

    In [161]: ts.resample('5Min', label='left', loffset='1s')
    Out[161]:
    2012-01-01 00:00:01    251.03
    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 time-stamp 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.

Note that 0.8 marks a watershed in the timeseries functionality in pandas. In previous versions, resampling had to be done using a combination of `date_range`, `groupby` with `asof`, and then calling an aggregation function on the grouped object. This was not nearly convenient or performant as the new pandas timeseries API.

## 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). It can be created using a frequency alias:

    In [162]: Period('2012', freq='A-DEC')
    Out[162]: Period('2012', 'A-DEC')

    In [163]: Period('2012-1-1', freq='D')
    Out[163]: Period('2012-01-01', 'D')

    In [164]: Period('2012-1-1 19:00', freq='H')
    Out[164]: Period('2012-01-01 19:00', 'H')

Unlike time stamped data, pandas does not support frequencies at multiples of DateOffsets (e.g., ‘3Min’) for periods.

Adding and subtracting integers from periods shifts the period by its own frequency.

    In [165]: p = Period('2012', freq='A-DEC')

    In [166]: p + 1
    Out[166]: Period('2013', 'A-DEC')

    In [167]: p - 3
    Out[167]: Period('2009', 'A-DEC')

Taking the difference of `Period` instances with the same frequency will return the number of frequency units between them:

    In [168]: Period('2012', freq='A-DEC') - Period('2002', freq='A-DEC')
    Out[168]: 10L

### 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:

    In [169]: prng = period_range('1/1/2011', '1/1/2012', freq='M')

    In [170]: prng
    Out[170]:
    <class 'pandas.tseries.period.PeriodIndex'>
    [2011-01, ..., 2012-01]
    Length: 13, Freq: M

The `PeriodIndex` constructor can also be used directly:

    In [171]: PeriodIndex(['2011-1', '2011-2', '2011-3'], freq='M')
    Out[171]:
    <class 'pandas.tseries.period.PeriodIndex'>
    [2011-01, ..., 2011-03]
    Length: 3, Freq: M

Just like `DatetimeIndex`, a `PeriodIndex` can also be used to index pandas objects:

    In [172]: ps = Series(randn(len(prng)), prng)

    In [173]: ps
    Out[173]:
    2011-01   -0.253355
    2011-02   -1.426908
    2011-03    1.548971
    2011-04   -0.088718
    2011-05   -1.771348
    2011-06   -0.989328
    2011-07   -1.584789
    2011-08   -0.288786
    2011-09   -2.029806
    2011-10   -0.761200
    2011-11   -1.603608
    2011-12    1.756171
    2012-01    0.256502
    Freq: M, dtype: float64

### PeriodIndex Partial String Indexing

You can pass in dates and strings to Series and DataFrame with PeriodIndex, as the same manner as DatetimeIndex. For details, refer to DatetimeIndex Partial String Indexing.

    In [174]: ps['2011-01']
    Out[174]: -0.25335528290092818

    In [175]: ps[datetime(2011, 12, 25):]
    Out[175]:
    2011-12    1.756171
    2012-01    0.256502
    Freq: M, dtype: float64

    In [176]: ps['10/31/2011':'12/31/2011']
    Out[176]:
    2011-10   -0.761200
    2011-11   -1.603608
    2011-12    1.756171
    Freq: M, dtype: float64

Passing string represents lower frequency than PeriodIndex returns partial sliced data.

    In [177]: ps['2011']
    Out[177]:
    2011-01   -0.253355
    2011-02   -1.426908
    2011-03    1.548971
    2011-04   -0.088718
    2011-05   -1.771348
    2011-06   -0.989328
    2011-07   -1.584789
    2011-08   -0.288786
    2011-09   -2.029806
    2011-10   -0.761200
    2011-11   -1.603608
    2011-12    1.756171
    Freq: M, dtype: float64

    In [178]: dfp = DataFrame(randn(600,1), columns=['A'],
       .....:                 index=period_range('2013-01-01 9:00', periods=600, freq='T'))
       .....:

    In [179]: dfp
    Out[179]:
                             A
    2013-01-01 09:00  0.020601
    2013-01-01 09:01 -0.411719
    2013-01-01 09:02  2.079413
    2013-01-01 09:03 -1.077911
    2013-01-01 09:04  0.099258
    2013-01-01 09:05 -0.089851
    2013-01-01 09:06  0.711329
    ...                    ...
    2013-01-01 18:53 -1.340038
    2013-01-01 18:54  1.315461
    2013-01-01 18:55  2.396188
    2013-01-01 18:56 -0.501527
    2013-01-01 18:57 -3.171938
    2013-01-01 18:58  0.142019
    2013-01-01 18:59  0.606998

    [600 rows x 1 columns]

    In [180]: dfp['2013-01-01 10H']
    Out[180]:
                             A
    2013-01-01 10:00 -0.745396
    2013-01-01 10:01  0.141880
    2013-01-01 10:02 -1.077754
    2013-01-01 10:03 -1.301174
    2013-01-01 10:04 -0.269628
    2013-01-01 10:05 -0.456347
    2013-01-01 10:06  0.157766
    ...                    ...
    2013-01-01 10:53  0.168057
    2013-01-01 10:54 -0.214306
    2013-01-01 10:55 -0.069739
    2013-01-01 10:56 -1.511809
    2013-01-01 10:57  0.307021
    2013-01-01 10:58  1.449776
    2013-01-01 10:59  0.782537

    [60 rows x 1 columns]

As the same as DatetimeIndex, the endpoints will be included in the result. Below example slices data starting from 10:00 to 11:59.

    In [181]: dfp['2013-01-01 10H':'2013-01-01 11H']
    Out[181]:
                             A
    2013-01-01 10:00 -0.745396
    2013-01-01 10:01  0.141880
    2013-01-01 10:02 -1.077754
    2013-01-01 10:03 -1.301174
    2013-01-01 10:04 -0.269628
    2013-01-01 10:05 -0.456347
    2013-01-01 10:06  0.157766
    ...                    ...
    2013-01-01 11:53 -0.064395
    2013-01-01 11:54  0.350193
    2013-01-01 11:55  1.336433
    2013-01-01 11:56 -0.438701
    2013-01-01 11:57 -0.915841
    2013-01-01 11:58  0.294215
    2013-01-01 11:59  0.040959

    [120 rows x 1 columns]

### Frequency Conversion and Resampling with PeriodIndex

The frequency of Periods and PeriodIndex can be converted via the `asfreq` method. Let’s start with the fiscal year 2011, ending in December:

    In [182]: p = Period('2011', freq='A-DEC')

    In [183]: p
    Out[183]: Period('2011', 'A-DEC')

We can convert it to a monthly frequency. Using the `how` parameter, we can specify whether to return the starting or ending month:

    In [184]: p.asfreq('M', how='start')
    Out[184]: Period('2011-01', 'M')

    In [185]: p.asfreq('M', how='end')
    Out[185]: Period('2011-12', 'M')

The shorthands ‘s’ and ‘e’ are provided for convenience:

    In [186]: p.asfreq('M', 's')
    Out[186]: Period('2011-01', 'M')

    In [187]: p.asfreq('M', 'e')
    Out[187]: 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 [188]: p = Period('2011-12', freq='M')

    In [189]: p.asfreq('A-NOV')
    Out[189]: Period('2012', 'A-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 A-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 start and ends. Thus, first quarter of 2011 could start in 2010 or a few months into 2011. Via anchored frequencies, pandas works all quarterly frequencies `Q-JAN` through `Q-DEC`.

`Q-DEC` define regular calendar quarters:

    In [190]: p = Period('2012Q1', freq='Q-DEC')

    In [191]: p.asfreq('D', 's')
    Out[191]: Period('2012-01-01', 'D')

    In [192]: p.asfreq('D', 'e')
    Out[192]: Period('2012-03-31', 'D')

`Q-MAR` defines fiscal year end in March:

    In [193]: p = Period('2011Q4', freq='Q-MAR')

    In [194]: p.asfreq('D', 's')
    Out[194]: Period('2011-01-01', 'D')

    In [195]: p.asfreq('D', 'e')
    Out[195]: Period('2011-03-31', 'D')

## Converting between Representations

Timestamped data can be converted to PeriodIndex-ed data using `to_period` and vice-versa using `to_timestamp`:

    In [196]: rng = date_range('1/1/2012', periods=5, freq='M')

    In [197]: ts = Series(randn(len(rng)), index=rng)

    In [198]: ts
    Out[198]:
    2012-01-31   -0.016142
    2012-02-29    0.865782
    2012-03-31    0.246439
    2012-04-30   -1.199736
    2012-05-31    0.407620
    Freq: M, dtype: float64

    In [199]: ps = ts.to_period()

    In [200]: ps
    Out[200]:
    2012-01   -0.016142
    2012-02    0.865782
    2012-03    0.246439
    2012-04   -1.199736
    2012-05    0.407620
    Freq: M, dtype: float64

    In [201]: ps.to_timestamp()
    Out[201]:
    2012-01-01   -0.016142
    2012-02-01    0.865782
    2012-03-01    0.246439
    2012-04-01   -1.199736
    2012-05-01    0.407620
    Freq: MS, dtype: float64

Remember that ‘s’ and ‘e’ can be used to return the timestamps at the start or end of the period:

    In [202]: ps.to_timestamp('D', how='s')
    Out[202]:
    2012-01-01   -0.016142
    2012-02-01    0.865782
    2012-03-01    0.246439
    2012-04-01   -1.199736
    2012-05-01    0.407620
    Freq: MS, dtype: float64

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 [203]: prng = period_range('1990Q1', '2000Q4', freq='Q-NOV')

    In [204]: ts = Series(randn(len(prng)), prng)

    In [205]: ts.index = (prng.asfreq('M', 'e') + 1).asfreq('H', 's') + 9

    In [206]: ts.head()
    Out[206]:
    1990-03-01 09:00   -2.470970
    1990-06-01 09:00   -0.929915
    1990-09-01 09:00    1.385889
    1990-12-01 09:00   -1.830966
    1991-03-01 09:00   -0.328505
    Freq: H, dtype: float64

## Time Zone Handling

Pandas provides rich support for working with timestamps in different time zones using `pytz` and `dateutil` libraries. `dateutil` support is new [in 0.14.1] and currently only supported for fixed offset and tzfile zones. The default library is `pytz`. Support for `dateutil` is provided for compatibility with other applications e.g. if you use `dateutil` in other python packages.

By default, pandas objects are time zone unaware:

    In [207]: rng = date_range('3/6/2012 00:00', periods=15, freq='D')

    In [208]: rng.tz is None
    Out[208]: True

To supply the time zone, you can use the `tz` keyword to `date_range` and other functions. Dateutil time zone strings are distinguished from `pytz` time zones by starting with `dateutil/`.

- In `pytz` you can find a list of common (and less common) time zones using `from pytz import common_timezones, all_timezones`.
- `dateutil` uses the OS timezones so there isn’t a fixed list available. For common zones, the names are the same as `pytz`.

    # pytz
    In [209]: rng_pytz = date_range('3/6/2012 00:00', periods=10, freq='D',
       .....:                       tz='Europe/London')
       .....:

    In [210]: rng_pytz.tz
    Out[210]: <DstTzInfo 'Europe/London' LMT-1 day, 23:59:00 STD>

    # dateutil
    In [211]: rng_dateutil = date_range('3/6/2012 00:00', periods=10, freq='D',
       .....:                           tz='dateutil/Europe/London')
       .....:

    In [212]: rng_dateutil.tz
    Out[212]: tzfile('/usr/share/zoneinfo/Europe/London')

    # dateutil - utc special case
    In [213]: rng_utc = date_range('3/6/2012 00:00', periods=10, freq='D',
       .....:                      tz=dateutil.tz.tzutc())
       .....:

    In [214]: rng_utc.tz
    Out[214]: tzutc()

Note that the `UTC` timezone is a special case in `dateutil` and should be constructed explicitly as an instance of `dateutil.tz.tzutc`. You can also construct other timezones explicitly first, which gives you more control over which time zone is used:

    # pytz
    In [215]: tz_pytz = pytz.timezone('Europe/London')

    In [216]: rng_pytz = date_range('3/6/2012 00:00', periods=10, freq='D',
       .....:                       tz=tz_pytz)
       .....:

    In [217]: rng_pytz.tz == tz_pytz
    Out[217]: True

    # dateutil
    In [218]: tz_dateutil = dateutil.tz.gettz('Europe/London')

    In [219]: rng_dateutil = date_range('3/6/2012 00:00', periods=10, freq='D',
       .....:                           tz=tz_dateutil)
       .....:

    In [220]: rng_dateutil.tz == tz_dateutil
    Out[220]: True

Timestamps, like Python’s `datetime.datetime` object can be either time zone naive or time zone aware. Naive time series and DatetimeIndex objects can be localized using `tz_localize`:

    In [221]: ts = Series(randn(len(rng)), rng)

    In [222]: ts_utc = ts.tz_localize('UTC')

    In [223]: ts_utc
    Out[223]:
    2012-03-06 00:00:00+00:00    0.758606
    2012-03-07 00:00:00+00:00    2.190827
    2012-03-08 00:00:00+00:00    0.706087
    2012-03-09 00:00:00+00:00    1.798831
    2012-03-10 00:00:00+00:00    1.228481
    2012-03-11 00:00:00+00:00   -0.179494
    2012-03-12 00:00:00+00:00    0.634073
    2012-03-13 00:00:00+00:00    0.262123
    2012-03-14 00:00:00+00:00    1.928233
    2012-03-15 00:00:00+00:00    0.322573
    2012-03-16 00:00:00+00:00   -0.711113
    2012-03-17 00:00:00+00:00    1.444272
    2012-03-18 00:00:00+00:00   -0.352268
    2012-03-19 00:00:00+00:00    0.213008
    2012-03-20 00:00:00+00:00   -0.619340
    Freq: D, dtype: float64

Again, you can explicitly construct the timezone object first. You can use the `tz_convert` method to convert pandas objects to convert tz-aware data to another time zone:

    In [224]: ts_utc.tz_convert('US/Eastern')
    Out[224]:
    2012-03-05 19:00:00-05:00    0.758606
    2012-03-06 19:00:00-05:00    2.190827
    2012-03-07 19:00:00-05:00    0.706087
    2012-03-08 19:00:00-05:00    1.798831
    2012-03-09 19:00:00-05:00    1.228481
    2012-03-10 19:00:00-05:00   -0.179494
    2012-03-11 20:00:00-04:00    0.634073
    2012-03-12 20:00:00-04:00    0.262123
    2012-03-13 20:00:00-04:00    1.928233
    2012-03-14 20:00:00-04:00    0.322573
    2012-03-15 20:00:00-04:00   -0.711113
    2012-03-16 20:00:00-04:00    1.444272
    2012-03-17 20:00:00-04:00   -0.352268
    2012-03-18 20:00:00-04:00    0.213008
    2012-03-19 20:00:00-04:00   -0.619340
    Freq: D, dtype: float64

Warning

Be wary of conversions between libraries. For some zones `pytz` and `dateutil` have different definitions of the zone. This is more of a problem for unusual timezones than for ‘standard’ zones like `US/Eastern`.

Warning

Be aware that a timezone definition across versions of timezone libraries may not be considered equal. This may cause problems when working with stored data that is localized using one version and operated on with a different version. See here for how to handle such a situation.

Under the hood, all timestamps are stored in UTC. Scalar values from a `DatetimeIndex` with a time zone will have their fields (day, hour, minute) 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:

    In [225]: rng_eastern = rng_utc.tz_convert('US/Eastern')

    In [226]: rng_berlin = rng_utc.tz_convert('Europe/Berlin')

    In [227]: rng_eastern[5]
    Out[227]: Timestamp('2012-03-10 19:00:00-0500', tz='US/Eastern', offset='D')

    In [228]: rng_berlin[5]
    Out[228]: Timestamp('2012-03-11 01:00:00+0100', tz='Europe/Berlin', offset='D')

    In [229]: rng_eastern[5] == rng_berlin[5]
    Out[229]: True

Like Series, DataFrame, and DatetimeIndex, Timestamps can be converted to other time zones using `tz_convert`:

    In [230]: rng_eastern[5]
    Out[230]: Timestamp('2012-03-10 19:00:00-0500', tz='US/Eastern', offset='D')

    In [231]: rng_berlin[5]
    Out[231]: Timestamp('2012-03-11 01:00:00+0100', tz='Europe/Berlin', offset='D')

    In [232]: rng_eastern[5].tz_convert('Europe/Berlin')
    Out[232]: Timestamp('2012-03-11 01:00:00+0100', tz='Europe/Berlin')

Localization of Timestamps functions just like DatetimeIndex and TimeSeries:

    In [233]: rng[5]
    Out[233]: Timestamp('2012-03-11 00:00:00', offset='D')

    In [234]: rng[5].tz_localize('Asia/Shanghai')
    Out[234]: Timestamp('2012-03-11 00:00:00+0800', tz='Asia/Shanghai')

Operations between TimeSeries in different time zones will yield UTC TimeSeries, aligning the data on the UTC timestamps:

    In [235]: eastern = ts_utc.tz_convert('US/Eastern')

    In [236]: berlin = ts_utc.tz_convert('Europe/Berlin')

    In [237]: result = eastern + berlin

    In [238]: result
    Out[238]:
    2012-03-06 00:00:00+00:00    1.517212
    2012-03-07 00:00:00+00:00    4.381654
    2012-03-08 00:00:00+00:00    1.412174
    2012-03-09 00:00:00+00:00    3.597662
    2012-03-10 00:00:00+00:00    2.456962
    2012-03-11 00:00:00+00:00   -0.358988
    2012-03-12 00:00:00+00:00    1.268146
    2012-03-13 00:00:00+00:00    0.524245
    2012-03-14 00:00:00+00:00    3.856466
    2012-03-15 00:00:00+00:00    0.645146
    2012-03-16 00:00:00+00:00   -1.422226
    2012-03-17 00:00:00+00:00    2.888544
    2012-03-18 00:00:00+00:00   -0.704537
    2012-03-19 00:00:00+00:00    0.426017
    2012-03-20 00:00:00+00:00   -1.238679
    Freq: D, dtype: float64

    In [239]: result.index
    Out[239]:
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2012-03-06, ..., 2012-03-20]
    Length: 15, Freq: D, Timezone: UTC

In some cases, localize cannot determine the DST and non-DST hours when there are duplicates. This often happens when reading files that simply duplicate the hours. The infer_dst argument in tz_localize will attempt to determine the right offset.

    In [240]: rng_hourly = DatetimeIndex(['11/06/2011 00:00', '11/06/2011 01:00',
       .....:                             '11/06/2011 01:00', '11/06/2011 02:00',
       .....:                             '11/06/2011 03:00'])
       .....:

    In [241]: rng_hourly.tz_localize('US/Eastern')
    ---------------------------------------------------------------------------
    AmbiguousTimeError                        Traceback (most recent call last)
    <ipython-input-241-8c5fa6a37f5b> in <module>()
    ----> 1 rng_hourly.tz_localize('US/Eastern')

    /home/joris/scipy/pandas/pandas/tseries/index.pyc in tz_localize(self, tz, infer_dst)
       1676
       1677         # Convert to UTC
    -> 1678         new_dates = tslib.tz_localize_to_utc(self.asi8, tz, infer_dst=infer_dst)
       1679         new_dates = new_dates.view(_NS_DTYPE)
       1680

    /home/joris/scipy/pandas/pandas/tslib.so in pandas.tslib.tz_localize_to_utc (pandas/tslib.c:34935)()

    AmbiguousTimeError: Cannot infer dst time from Timestamp('2011-11-06 01:00:00'), try using the 'infer_dst' argument

    In [242]: rng_hourly_eastern = rng_hourly.tz_localize('US/Eastern', infer_dst=True)

    In [243]: rng_hourly_eastern.values
    Out[243]:
    array(['2011-11-06T05:00:00.000000000+0100',
           '2011-11-06T06:00:00.000000000+0100',
           '2011-11-06T07:00:00.000000000+0100',
           '2011-11-06T08:00:00.000000000+0100',
           '2011-11-06T09:00:00.000000000+0100'], dtype='datetime64[ns]')

## Time Deltas

Timedeltas are differences in times, expressed in difference units, e.g. days,hours,minutes,seconds. They can be both positive and negative. DateOffsets that are absolute in nature (`Day, Hour, Minute, Second, Milli, Micro, Nano`) can be used as `timedeltas`.

    In [244]: from datetime import datetime, timedelta

    In [245]: s = Series(date_range('2012-1-1', periods=3, freq='D'))

    In [246]: td = Series([ timedelta(days=i) for i in range(3) ])

    In [247]: df = DataFrame(dict(A = s, B = td))

    In [248]: df
    Out[248]:
               A      B
    0 2012-01-01 0 days
    1 2012-01-02 1 days
    2 2012-01-03 2 days

    In [249]: df['C'] = df['A'] + df['B']

    In [250]: df
    Out[250]:
               A      B          C
    0 2012-01-01 0 days 2012-01-01
    1 2012-01-02 1 days 2012-01-03
    2 2012-01-03 2 days 2012-01-05

    In [251]: df.dtypes
    Out[251]:
    A     datetime64[ns]
    B    timedelta64[ns]
    C     datetime64[ns]
    dtype: object

    In [252]: s - s.max()
    Out[252]:
    0   -2 days
    1   -1 days
    2    0 days
    dtype: timedelta64[ns]

    In [253]: s - datetime(2011,1,1,3,5)
    Out[253]:
    0   364 days, 20:55:00
    1   365 days, 20:55:00
    2   366 days, 20:55:00
    dtype: timedelta64[ns]

    In [254]: s + timedelta(minutes=5)
    Out[254]:
    0   2012-01-01 00:05:00
    1   2012-01-02 00:05:00
    2   2012-01-03 00:05:00
    dtype: datetime64[ns]

    In [255]: s + Minute(5)
    Out[255]:
    0   2012-01-01 00:05:00
    1   2012-01-02 00:05:00
    2   2012-01-03 00:05:00
    dtype: datetime64[ns]

    In [256]: s + Minute(5) + Milli(5)
    Out[256]:
    0   2012-01-01 00:05:00.005000
    1   2012-01-02 00:05:00.005000
    2   2012-01-03 00:05:00.005000
    dtype: datetime64[ns]

Getting scalar results from a `timedelta64[ns]` series

    In [257]: y = s - s[0]

    In [258]: y
    Out[258]:
    0   0 days
    1   1 days
    2   2 days
    dtype: timedelta64[ns]

Series of timedeltas with `NaT` values are supported

    In [259]: y = s - s.shift()

    In [260]: y
    Out[260]:
    0      NaT
    1   1 days
    2   1 days
    dtype: timedelta64[ns]

Elements can be set to `NaT` using `np.nan` analagously to datetimes

    In [261]: y[1] = np.nan

    In [262]: y
    Out[262]:
    0      NaT
    1      NaT
    2   1 days
    dtype: timedelta64[ns]

Operands can also appear in a reversed order (a singular object operated with a Series)

    In [263]: s.max() - s
    Out[263]:
    0   2 days
    1   1 days
    2   0 days
    dtype: timedelta64[ns]

    In [264]: datetime(2011,1,1,3,5) - s
    Out[264]:
    0   -364 days, 20:55:00
    1   -365 days, 20:55:00
    2   -366 days, 20:55:00
    dtype: timedelta64[ns]

    In [265]: timedelta(minutes=5) + s
    Out[265]:
    0   2012-01-01 00:05:00
    1   2012-01-02 00:05:00
    2   2012-01-03 00:05:00
    dtype: datetime64[ns]

Some timedelta numeric like operations are supported.

    In [266]: td - timedelta(minutes=5, seconds=5, microseconds=5)
    Out[266]:
    0   -0 days, 00:05:05.000005
    1    0 days, 23:54:54.999995
    2    1 days, 23:54:54.999995
    dtype: timedelta64[ns]

`min, max` and the corresponding `idxmin, idxmax` operations are supported on frames

    In [267]: A = s - Timestamp('20120101') - timedelta(minutes=5, seconds=5)

    In [268]: B = s - Series(date_range('2012-1-2', periods=3, freq='D'))

    In [269]: df = DataFrame(dict(A=A, B=B))

    In [270]: df
    Out[270]:
                      A       B
    0 -0 days, 00:05:05 -1 days
    1  0 days, 23:54:55 -1 days
    2  1 days, 23:54:55 -1 days

    In [271]: df.min()
    Out[271]:
    A   -0 days, 00:05:05
    B   -1 days, 00:00:00
    dtype: timedelta64[ns]

    In [272]: df.min(axis=1)
    Out[272]:
    0   -1 days
    1   -1 days
    2   -1 days
    dtype: timedelta64[ns]

    In [273]: df.idxmin()
    Out[273]:
    A    0
    B    0
    dtype: int64

    In [274]: df.idxmax()
    Out[274]:
    A    2
    B    0
    dtype: int64

`min, max` operations are supported on series; these return a single element `timedelta64[ns]` Series (this avoids having to deal with numpy timedelta64 issues). `idxmin, idxmax` are supported as well.

    In [275]: df.min().max()
    Out[275]:
    0   -00:05:05
    dtype: timedelta64[ns]

    In [276]: df.min(axis=1).min()
    Out[276]:
    0   -1 days
    dtype: timedelta64[ns]

    In [277]: df.min().idxmax()
    Out[277]: 'A'

    In [278]: df.min(axis=1).idxmin()
    Out[278]: 0

You can fillna on timedeltas. Integers will be interpreted as seconds. You can pass a timedelta to get a particular value.

    In [279]: y.fillna(0)
    Out[279]:
    0   0 days
    1   0 days
    2   1 days
    dtype: timedelta64[ns]

    In [280]: y.fillna(10)
    Out[280]:
    0   0 days, 00:00:10
    1   0 days, 00:00:10
    2   1 days, 00:00:00
    dtype: timedelta64[ns]

    In [281]: y.fillna(timedelta(days=-1,seconds=5))
    Out[281]:
    0   -0 days, 23:59:55
    1   -0 days, 23:59:55
    2    1 days, 00:00:00
    dtype: timedelta64[ns]

## Time Deltas & Reductions

Warning

A numeric reduction operation for `timedelta64[ns]` can return a single-element `Series` of dtype `timedelta64[ns]`.

You can do numeric reduction operations on timedeltas.

    In [282]: y2 = y.fillna(timedelta(days=-1,seconds=5))

    In [283]: y2
    Out[283]:
    0   -0 days, 23:59:55
    1   -0 days, 23:59:55
    2    1 days, 00:00:00
    dtype: timedelta64[ns]

    In [284]: y2.mean()
    Out[284]:
    0   -07:59:56.666667
    dtype: timedelta64[ns]

    In [285]: y2.quantile(.1)
    Out[285]: numpy.timedelta64(-86395000000000,'ns')

## Time Deltas & Conversions

New in version 0.13.

string/integer conversion

Using the top-level `to_timedelta`, you can convert a scalar or array from the standard timedelta format (produced by `to_csv`) into a timedelta type (`np.timedelta64` in `nanoseconds`). It can also construct Series.

Warning

This requires `numpy >= 1.7`

    In [286]: to_timedelta('1 days 06:05:01.00003')
    Out[286]: numpy.timedelta64(108301000030000,'ns')

    In [287]: to_timedelta('15.5us')
    Out[287]: numpy.timedelta64(15500,'ns')

    In [288]: to_timedelta(['1 days 06:05:01.00003','15.5us','nan'])
    Out[288]:
    0   1 days, 06:05:01.000030
    1   0 days, 00:00:00.000016
    2                       NaT
    dtype: timedelta64[ns]

    In [289]: to_timedelta(np.arange(5),unit='s')
    Out[289]:
    0   00:00:00
    1   00:00:01
    2   00:00:02
    3   00:00:03
    4   00:00:04
    dtype: timedelta64[ns]

    In [290]: to_timedelta(np.arange(5),unit='d')
    Out[290]:
    0   0 days
    1   1 days
    2   2 days
    3   3 days
    4   4 days
    dtype: timedelta64[ns]

frequency conversion

Timedeltas can be converted to other ‘frequencies’ by dividing by another timedelta, or by astyping to a specific timedelta type. These operations yield `float64` dtyped Series.

    In [291]: td = Series(date_range('20130101',periods=4))-Series(date_range('20121201',periods=4))

    In [292]: td[2] += np.timedelta64(timedelta(minutes=5,seconds=3))

    In [293]: td[3] = np.nan

    In [294]: td
    Out[294]:
    0   31 days, 00:00:00
    1   31 days, 00:00:00
    2   31 days, 00:05:03
    3                 NaT
    dtype: timedelta64[ns]

    # to days
    In [295]: td / np.timedelta64(1,'D')
    Out[295]:
    0    31.000000
    1    31.000000
    2    31.003507
    3          NaN
    dtype: float64

    In [296]: td.astype('timedelta64[D]')
    Out[296]:
    0    31
    1    31
    2    31
    3   NaN
    dtype: float64

    # to seconds
    In [297]: td / np.timedelta64(1,'s')
    Out[297]:
    0    2678400
    1    2678400
    2    2678703
    3        NaN
    dtype: float64

    In [298]: td.astype('timedelta64[s]')
    Out[298]:
    0    2678400
    1    2678400
    2    2678703
    3        NaN
    dtype: float64

Dividing or multiplying a `timedelta64[ns]` Series by an integer or integer Series yields another `timedelta64[ns]` dtypes Series.

    In [299]: td * -1
    Out[299]:
    0   -31 days, 00:00:00
    1   -31 days, 00:00:00
    2   -31 days, 00:05:03
    3                  NaT
    dtype: timedelta64[ns]

    In [300]: td * Series([1,2,3,4])
    Out[300]:
    0   31 days, 00:00:00
    1   62 days, 00:00:00
    2   93 days, 00:15:09
    3                 NaT
    dtype: timedelta64[ns]

### Numpy < 1.7 Compatibility

Numpy < 1.7 has a broken `timedelta64` type that does not correctly work for arithmetic. pandas bypasses this, but for frequency conversion as above, you need to create the divisor yourself. The `np.timetimedelta64` type only has 1 argument, the number of micro seconds.

The following are equivalent statements in the two versions of numpy.

    from distutils.version import LooseVersion
    if LooseVersion(np.__version__) <= '1.6.2':
        y / np.timedelta(86400*int(1e6))
        y / np.timedelta(int(1e6))
    else:
        y / np.timedelta64(1,'D')
        y / np.timedelta64(1,'s')

### Navigation

- index
- modules |
- next |
- previous |
- pandas 0.14.1 documentation »