Table Of Contents

Search

Enter search terms or a module, class or function name.

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. Using the NumPy datetime64 and timedelta64 dtypes, 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 = pd.date_range('1/1/2011', periods=72, freq='H')

In [2]: rng[:5]
Out[2]: 
DatetimeIndex(['2011-01-01 00:00:00', '2011-01-01 01:00:00',
               '2011-01-01 02:00:00', '2011-01-01 03:00:00',
               '2011-01-01 04:00:00'],
              dtype='datetime64[ns]', freq='H')

Index pandas objects with dates:

In [3]: ts = pd.Series(np.random.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').mean()
Out[7]: 
2011-01-01   -0.319569
2011-01-02   -0.337703
2011-01-03    0.117258
Freq: D, dtype: float64

Overview

Following table shows the type of time-related classes pandas can handle and how to create them.

Class Remarks How to create
Timestamp Represents a single time stamp to_datetime, Timestamp
DatetimeIndex Index of Timestamp to_datetime, date_range, DatetimeIndex
Period Represents a single time span Period
PeriodIndex Index of Period period_range, PeriodIndex

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.

In [8]: pd.Timestamp(datetime(2012, 5, 1))
Out[8]: Timestamp('2012-05-01 00:00:00')

In [9]: pd.Timestamp('2012-05-01')
Out[9]: Timestamp('2012-05-01 00:00:00')

In [10]: pd.Timestamp(2012, 5, 1)
Out[10]: Timestamp('2012-05-01 00:00:00')

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 [11]: pd.Period('2011-01')
Out[11]: Period('2011-01', 'M')

In [12]: pd.Period('2012-05', freq='D')
Out[12]: Period('2012-05-01', 'D')

Timestamp and Period can be the index. Lists of Timestamp and Period are automatically coerced to DatetimeIndex and PeriodIndex respectively.

In [13]: dates = [pd.Timestamp('2012-05-01'), pd.Timestamp('2012-05-02'), pd.Timestamp('2012-05-03')]

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

In [15]: type(ts.index)
Out[15]: pandas.core.indexes.datetimes.DatetimeIndex

In [16]: ts.index
Out[16]: DatetimeIndex(['2012-05-01', '2012-05-02', '2012-05-03'], dtype='datetime64[ns]', freq=None)

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

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

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

In [20]: type(ts.index)
Out[20]: pandas.core.indexes.period.PeriodIndex

In [21]: ts.index
Out[21]: PeriodIndex(['2012-01', '2012-02', '2012-03'], dtype='period[M]', freq='M')

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

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 [23]: pd.to_datetime(pd.Series(['Jul 31, 2009', '2010-01-10', None]))
Out[23]: 
0   2009-07-31
1   2010-01-10
2          NaT
dtype: datetime64[ns]

In [24]: pd.to_datetime(['2005/11/23', '2010.12.31'])
Out[24]: DatetimeIndex(['2005-11-23', '2010-12-31'], dtype='datetime64[ns]', freq=None)

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

In [25]: pd.to_datetime(['04-01-2012 10:00'], dayfirst=True)
Out[25]: DatetimeIndex(['2012-01-04 10:00:00'], dtype='datetime64[ns]', freq=None)

In [26]: pd.to_datetime(['14-01-2012', '01-14-2012'], dayfirst=True)
Out[26]: DatetimeIndex(['2012-01-14', '2012-01-14'], dtype='datetime64[ns]', freq=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.

If you pass a single string to to_datetime, it returns single Timestamp. Also, Timestamp can accept the string input. Note that Timestamp doesn’t accept string parsing option like dayfirst or format, use to_datetime if these are required.

In [27]: pd.to_datetime('2010/11/12')
Out[27]: Timestamp('2010-11-12 00:00:00')

In [28]: pd.Timestamp('2010/11/12')
Out[28]: Timestamp('2010-11-12 00:00:00')

New in version 0.18.1.

You can also pass a DataFrame of integer or string columns to assemble into a Series of Timestamps.

In [29]: df = pd.DataFrame({'year': [2015, 2016],
   ....:                    'month': [2, 3],
   ....:                    'day': [4, 5],
   ....:                    'hour': [2, 3]})
   ....: 

In [30]: pd.to_datetime(df)
Out[30]: 
0   2015-02-04 02:00:00
1   2016-03-05 03:00:00
dtype: datetime64[ns]

You can pass only the columns that you need to assemble.

In [31]: pd.to_datetime(df[['year', 'month', 'day']])
Out[31]: 
0   2015-02-04
1   2016-03-05
dtype: datetime64[ns]

pd.to_datetime looks for standard designations of the datetime component in the column names, including:

  • required: year, month, day
  • optional: hour, minute, second, millisecond, microsecond, nanosecond

Invalid Data

Note

In version 0.17.0, the default for to_datetime is now errors='raise', rather than errors='ignore'. This means that invalid parsing will raise rather that return the original input as in previous versions.

Pass errors='coerce' to convert invalid data to NaT (not a time):

Raise when unparseable, this is the default

In [2]: pd.to_datetime(['2009/07/31', 'asd'], errors='raise')
ValueError: Unknown string format

Return the original input when unparseable

In [4]: pd.to_datetime(['2009/07/31', 'asd'], errors='ignore')
Out[4]: array(['2009/07/31', 'asd'], dtype=object)

Return NaT for input when unparseable

In [6]: pd.to_datetime(['2009/07/31', 'asd'], errors='coerce')
Out[6]: DatetimeIndex(['2009-07-31', 'NaT'], dtype='datetime64[ns]', freq=None)

Epoch Timestamps

It’s also possible to convert integer or float epoch times. The default unit for these is nanoseconds (since these are how Timestamp s are stored). However, often epochs are stored in another unit which can be specified. These are computed from the starting point specified by the Origin Parameter.

Typical epoch stored units

In [32]: pd.to_datetime([1349720105, 1349806505, 1349892905,
   ....:                 1349979305, 1350065705], unit='s')
   ....: 
Out[32]: 
DatetimeIndex(['2012-10-08 18:15:05', '2012-10-09 18:15:05',
               '2012-10-10 18:15:05', '2012-10-11 18:15:05',
               '2012-10-12 18:15:05'],
              dtype='datetime64[ns]', freq=None)

In [33]: pd.to_datetime([1349720105100, 1349720105200, 1349720105300,
   ....:                 1349720105400, 1349720105500 ], unit='ms')
   ....: 
Out[33]: 
DatetimeIndex(['2012-10-08 18:15:05.100000', '2012-10-08 18:15:05.200000',
               '2012-10-08 18:15:05.300000', '2012-10-08 18:15:05.400000',
               '2012-10-08 18:15:05.500000'],
              dtype='datetime64[ns]', freq=None)

Note

Epoch times will be rounded to the nearest nanosecond.

Warning

Conversion of float epoch times can lead to inaccurate and unexpected results. Python floats have about 15 digits precision in decimal. Rounding during conversion from float to high precision Timestamp is unavoidable. The only way to achieve exact precision is to use a fixed-width types (e.g. an int64).

In [34]: pd.to_datetime([1490195805.433, 1490195805.433502912], unit='s')
Out[34]: DatetimeIndex(['2017-03-22 15:16:45.433000', '2017-03-22 15:16:45.433503'], dtype='datetime64[ns]', freq=None)

In [35]: pd.to_datetime(1490195805433502912, unit='ns')
Out[35]: Timestamp('2017-03-22 15:16:45.433502912')

From Timestamps to Epoch

To invert the operation from above, namely, to convert from a Timestamp to a ‘unix’ epoch:

In [36]: stamps = pd.date_range('2012-10-08 18:15:05', periods=4, freq='D')

In [37]: stamps
Out[37]: 
DatetimeIndex(['2012-10-08 18:15:05', '2012-10-09 18:15:05',
               '2012-10-10 18:15:05', '2012-10-11 18:15:05'],
              dtype='datetime64[ns]', freq='D')

We convert the DatetimeIndex to an int64 array, then divide by the conversion unit.

In [38]: stamps.view('int64') // pd.Timedelta(1, unit='s')
Out[38]: array([1349720105, 1349806505, 1349892905, 1349979305])

Using the Origin Parameter

New in version 0.20.0.

Using the origin parameter, one can specify an alternative starting point for creation of a DatetimeIndex.

Start with 1960-01-01 as the starting date

In [39]: pd.to_datetime([1, 2, 3], unit='D', origin=pd.Timestamp('1960-01-01'))
Out[39]: DatetimeIndex(['1960-01-02', '1960-01-03', '1960-01-04'], dtype='datetime64[ns]', freq=None)

The default is set at origin='unix', which defaults to 1970-01-01 00:00:00. Commonly called ‘unix epoch’ or POSIX time.

In [40]: pd.to_datetime([1, 2, 3], unit='D')
Out[40]: DatetimeIndex(['1970-01-02', '1970-01-03', '1970-01-04'], dtype='datetime64[ns]', freq=None)

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 [41]: dates = [datetime(2012, 5, 1), datetime(2012, 5, 2), datetime(2012, 5, 3)]

# Note the frequency information
In [42]: index = pd.DatetimeIndex(dates)

In [43]: index
Out[43]: DatetimeIndex(['2012-05-01', '2012-05-02', '2012-05-03'], dtype='datetime64[ns]', freq=None)

# Automatically converted to DatetimeIndex
In [44]: index = pd.Index(dates)

In [45]: index
Out[45]: DatetimeIndex(['2012-05-01', '2012-05-02', '2012-05-03'], dtype='datetime64[ns]', freq=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 [46]: index = pd.date_range('2000-1-1', periods=1000, freq='M')

In [47]: index
Out[47]: 
DatetimeIndex(['2000-01-31', '2000-02-29', '2000-03-31', '2000-04-30',
               '2000-05-31', '2000-06-30', '2000-07-31', '2000-08-31',
               '2000-09-30', '2000-10-31',
               ...
               '2082-07-31', '2082-08-31', '2082-09-30', '2082-10-31',
               '2082-11-30', '2082-12-31', '2083-01-31', '2083-02-28',
               '2083-03-31', '2083-04-30'],
              dtype='datetime64[ns]', length=1000, freq='M')

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

In [49]: index
Out[49]: 
DatetimeIndex(['2012-01-02', '2012-01-03', '2012-01-04', '2012-01-05',
               '2012-01-06', '2012-01-09', '2012-01-10', '2012-01-11',
               '2012-01-12', '2012-01-13',
               ...
               '2012-12-03', '2012-12-04', '2012-12-05', '2012-12-06',
               '2012-12-07', '2012-12-10', '2012-12-11', '2012-12-12',
               '2012-12-13', '2012-12-14'],
              dtype='datetime64[ns]', length=250, freq='B')

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 [50]: start = datetime(2011, 1, 1)

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

In [52]: rng = pd.date_range(start, end)

In [53]: rng
Out[53]: 
DatetimeIndex(['2011-01-01', '2011-01-02', '2011-01-03', '2011-01-04',
               '2011-01-05', '2011-01-06', '2011-01-07', '2011-01-08',
               '2011-01-09', '2011-01-10',
               ...
               '2011-12-23', '2011-12-24', '2011-12-25', '2011-12-26',
               '2011-12-27', '2011-12-28', '2011-12-29', '2011-12-30',
               '2011-12-31', '2012-01-01'],
              dtype='datetime64[ns]', length=366, freq='D')

In [54]: rng = pd.bdate_range(start, end)

In [55]: rng
Out[55]: 
DatetimeIndex(['2011-01-03', '2011-01-04', '2011-01-05', '2011-01-06',
               '2011-01-07', '2011-01-10', '2011-01-11', '2011-01-12',
               '2011-01-13', '2011-01-14',
               ...
               '2011-12-19', '2011-12-20', '2011-12-21', '2011-12-22',
               '2011-12-23', '2011-12-26', '2011-12-27', '2011-12-28',
               '2011-12-29', '2011-12-30'],
              dtype='datetime64[ns]', length=260, freq='B')

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:

In [56]: pd.date_range(start, end, freq='BM')
Out[56]: 
DatetimeIndex(['2011-01-31', '2011-02-28', '2011-03-31', '2011-04-29',
               '2011-05-31', '2011-06-30', '2011-07-29', '2011-08-31',
               '2011-09-30', '2011-10-31', '2011-11-30', '2011-12-30'],
              dtype='datetime64[ns]', freq='BM')

In [57]: pd.date_range(start, end, freq='W')
Out[57]: 
DatetimeIndex(['2011-01-02', '2011-01-09', '2011-01-16', '2011-01-23',
               '2011-01-30', '2011-02-06', '2011-02-13', '2011-02-20',
               '2011-02-27', '2011-03-06', '2011-03-13', '2011-03-20',
               '2011-03-27', '2011-04-03', '2011-04-10', '2011-04-17',
               '2011-04-24', '2011-05-01', '2011-05-08', '2011-05-15',
               '2011-05-22', '2011-05-29', '2011-06-05', '2011-06-12',
               '2011-06-19', '2011-06-26', '2011-07-03', '2011-07-10',
               '2011-07-17', '2011-07-24', '2011-07-31', '2011-08-07',
               '2011-08-14', '2011-08-21', '2011-08-28', '2011-09-04',
               '2011-09-11', '2011-09-18', '2011-09-25', '2011-10-02',
               '2011-10-09', '2011-10-16', '2011-10-23', '2011-10-30',
               '2011-11-06', '2011-11-13', '2011-11-20', '2011-11-27',
               '2011-12-04', '2011-12-11', '2011-12-18', '2011-12-25',
               '2012-01-01'],
              dtype='datetime64[ns]', freq='W-SUN')

In [58]: pd.bdate_range(end=end, periods=20)
Out[58]: 
DatetimeIndex(['2011-12-05', '2011-12-06', '2011-12-07', '2011-12-08',
               '2011-12-09', '2011-12-12', '2011-12-13', '2011-12-14',
               '2011-12-15', '2011-12-16', '2011-12-19', '2011-12-20',
               '2011-12-21', '2011-12-22', '2011-12-23', '2011-12-26',
               '2011-12-27', '2011-12-28', '2011-12-29', '2011-12-30'],
              dtype='datetime64[ns]', freq='B')

In [59]: pd.bdate_range(start=start, periods=20)
Out[59]: 
DatetimeIndex(['2011-01-03', '2011-01-04', '2011-01-05', '2011-01-06',
               '2011-01-07', '2011-01-10', '2011-01-11', '2011-01-12',
               '2011-01-13', '2011-01-14', '2011-01-17', '2011-01-18',
               '2011-01-19', '2011-01-20', '2011-01-21', '2011-01-24',
               '2011-01-25', '2011-01-26', '2011-01-27', '2011-01-28'],
              dtype='datetime64[ns]', freq='B')

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

Timestamp limitations

Since pandas represents timestamps in nanosecond resolution, the timespan that can be represented using a 64-bit integer is limited to approximately 584 years:

In [60]: pd.Timestamp.min
Out[60]: Timestamp('1677-09-21 00:12:43.145225')

In [61]: pd.Timestamp.max
Out[61]: Timestamp('2262-04-11 23:47:16.854775807')

See here for ways to represent data outside these bound.

Indexing

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.

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 [62]: rng = pd.date_range(start, end, freq='BM')

In [63]: ts = pd.Series(np.random.randn(len(rng)), index=rng)

In [64]: ts.index
Out[64]: 
DatetimeIndex(['2011-01-31', '2011-02-28', '2011-03-31', '2011-04-29',
               '2011-05-31', '2011-06-30', '2011-07-29', '2011-08-31',
               '2011-09-30', '2011-10-31', '2011-11-30', '2011-12-30'],
              dtype='datetime64[ns]', freq='BM')

In [65]: ts[:5].index
Out[65]: 
DatetimeIndex(['2011-01-31', '2011-02-28', '2011-03-31', '2011-04-29',
               '2011-05-31'],
              dtype='datetime64[ns]', freq='BM')

In [66]: ts[::2].index
Out[66]: 
DatetimeIndex(['2011-01-31', '2011-03-31', '2011-05-31', '2011-07-29',
               '2011-09-30', '2011-11-30'],
              dtype='datetime64[ns]', freq='2BM')

Partial String Indexing

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

In [67]: ts['1/31/2011']
Out[67]: -1.2812473076599531

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

In [69]: ts['10/31/2011':'12/31/2011']
Out[69]: 
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 [70]: ts['2011']
Out[70]: 
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 [71]: ts['2011-6']
Out[71]: 
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 [72]: dft = pd.DataFrame(randn(100000,1),
   ....:                    columns=['A'],
   ....:                    index=pd.date_range('20130101',periods=100000,freq='T'))
   ....: 

In [73]: dft
Out[73]: 
                            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 [74]: dft['2013']
Out[74]: 
                            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 [75]: dft['2013-1':'2013-2']
Out[75]: 
                            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 [76]: dft['2013-1':'2013-2-28']
Out[76]: 
                            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 [77]: dft['2013-1':'2013-2-28 00:00:00']
Out[77]: 
                            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 it is part of the index

In [78]: dft['2013-1-15':'2013-1-15 12:30:00']
Out[78]: 
                            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]

New in version 0.18.0.

DatetimeIndex Partial String Indexing also works on DataFrames with a MultiIndex. For example:

In [79]: 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 [80]: dft2
Out[80]: 
                              A
2013-01-01 00:00:00 a -0.659574
                    b  1.494522
2013-01-01 12:00:00 a -0.778425
                    b -0.253355
2013-01-02 00:00:00 a -2.816159
                    b -1.210929
2013-01-02 12:00:00 a  0.144669
...                         ...
2013-01-04 00:00:00 b -1.624463
2013-01-04 12:00:00 a  0.056912
                    b  0.149867
2013-01-05 00:00:00 a -1.256173
                    b  2.324544
2013-01-05 12:00:00 a -1.067396
                    b -0.660996

[20 rows x 1 columns]

In [81]: dft2.loc['2013-01-05']
Out[81]: 
                              A
2013-01-05 00:00:00 a -1.256173
                    b  2.324544
2013-01-05 12:00:00 a -1.067396
                    b -0.660996

In [82]: idx = pd.IndexSlice

In [83]: dft2 = dft2.swaplevel(0, 1).sort_index()

In [84]: dft2.loc[idx[:, '2013-01-05'], :]
Out[84]: 
                              A
a 2013-01-05 00:00:00 -1.256173
  2013-01-05 12:00:00 -1.067396
b 2013-01-05 00:00:00  2.324544
  2013-01-05 12:00:00 -0.660996

Slice vs. exact match

Changed in version 0.20.0.

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 an index. If the string is less accurate than the index, it will be treated as a slice, otherwise as an exact match.

For example, let us consider Series object which index has minute resolution.

In [85]: series_minute = pd.Series([1, 2, 3],
   ....:                           pd.DatetimeIndex(['2011-12-31 23:59:00',
   ....:                                             '2012-01-01 00:00:00',
   ....:                                             '2012-01-01 00:02:00']))
   ....: 

In [86]: series_minute.index.resolution
Out[86]: 'minute'

A timestamp string less accurate than a minute gives a Series object.

In [87]: series_minute['2011-12-31 23']
Out[87]: 
2011-12-31 23:59:00    1
dtype: int64

A timestamp string with minute resolution (or more accurate), gives a scalar instead, i.e. it is not casted to a slice.

In [88]: series_minute['2011-12-31 23:59']
Out[88]: 1

In [89]: series_minute['2011-12-31 23:59:00']
Out[89]: 1

If index resolution is second, then, the minute-accurate timestamp gives a Series.

In [90]: series_second = pd.Series([1, 2, 3],
   ....:                           pd.DatetimeIndex(['2011-12-31 23:59:59',
   ....:                                             '2012-01-01 00:00:00',
   ....:                                             '2012-01-01 00:00:01']))
   ....: 

In [91]: series_second.index.resolution
Out[91]: 'second'

In [92]: series_second['2011-12-31 23:59']
Out[92]: 
2011-12-31 23:59:59    1
dtype: int64

If the timestamp string is treated as a slice, it can be used to index DataFrame with [] as well.

In [93]: dft_minute = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]},
   ....:                            index=series_minute.index)
   ....: 

In [94]: dft_minute['2011-12-31 23']
Out[94]: 
                     a  b
2011-12-31 23:59:00  1  4

Warning

However if the string is treated as an exact match, the selection in DataFrame’s [] will be column-wise and not row-wise, see Indexing Basics. For example dft_minute['2011-12-31 23:59'] will raise KeyError as '2012-12-31 23:59' has the same resolution as index and there is no column with such name:

To always have unambiguous selection, whether the row is treated as a slice or a single selection, use .loc.

In [95]: dft_minute.loc['2011-12-31 23:59']
Out[95]: 
a    1
b    4
Name: 2011-12-31 23:59:00, dtype: int64

Note also that DatetimeIndex resolution cannot be less precise than day.

In [96]: series_monthly = pd.Series([1, 2, 3],
   ....:                           pd.DatetimeIndex(['2011-12',
   ....:                                             '2012-01',
   ....:                                             '2012-02']))
   ....: 

In [97]: series_monthly.index.resolution
Out[97]: 'day'

In [98]: series_monthly['2011-12'] # returns Series
Out[98]: 
2011-12-01    1
dtype: int64

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).

In [99]: dft[datetime(2013, 1, 1):datetime(2013,2,28)]
Out[99]: 
                            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 [100]: dft[datetime(2013, 1, 1, 10, 12, 0):datetime(2013, 2, 28, 10, 12, 0)]
Out[100]: 
                            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 [101]: ts.truncate(before='10/31/2011', after='12/31/2011')
Out[101]: 
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 [102]: ts[[0, 2, 6]].index
Out[102]: DatetimeIndex(['2011-01-31', '2011-03-31', '2011-07-29'], dtype='datetime64[ns]', freq=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 (does not contain timezone information)
time Returns datetime.time (does not contain timezone information)
dayofyear 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
weekday The number of the day of the week with Monday=0, Sunday=6
weekday_name The name of the day in a week (ex: Friday)
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, see the docs

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
SemiMonthEnd 15th (or other day_of_month) and calendar month end
SemiMonthBegin 15th (or other day_of_month) and calendar 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
BusinessHour business hour
CustomBusinessHour custom business hour
Hour one hour
Minute one minute
Second one second
Milli one millisecond
Micro one microsecond
Nano one nanosecond

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

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

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

We could have done the same thing with DateOffset:

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

In [106]: d + DateOffset(months=4, days=5)
Out[106]: 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 [107]: d - 5 * BDay()
Out[107]: Timestamp('2008-08-11 09:00:00')

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

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

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

In [110]: offset = BMonthEnd()

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

In [112]: offset.rollback(d)
Out[112]: 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 creating the offset instance. If normalize=True, result is normalized after the function is applied.

In [113]: day = Day()

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

In [115]: day = Day(normalize=True)

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

In [117]: hour = Hour()

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

In [119]: hour = Hour(normalize=True)

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

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

Parametric offsets

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:

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

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

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

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

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

normalize option will be effective for addition and subtraction.

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

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

Another example is parameterizing YearEnd with the specific ending month:

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

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

Using offsets with Series / DatetimeIndex

Offsets can be used with either a Series or DatetimeIndex to apply the offset to each element.

In [131]: rng = pd.date_range('2012-01-01', '2012-01-03')

In [132]: s = pd.Series(rng)

In [133]: rng
Out[133]: DatetimeIndex(['2012-01-01', '2012-01-02', '2012-01-03'], dtype='datetime64[ns]', freq='D')

In [134]: rng + DateOffset(months=2)
Out[134]: DatetimeIndex(['2012-03-01', '2012-03-02', '2012-03-03'], dtype='datetime64[ns]', freq='D')

In [135]: s + DateOffset(months=2)
Out[135]: 
0   2012-03-01
1   2012-03-02
2   2012-03-03
dtype: datetime64[ns]

In [136]: s - DateOffset(months=2)
Out[136]: 
0   2011-11-01
1   2011-11-02
2   2011-11-03
dtype: datetime64[ns]

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 [137]: s - Day(2)
Out[137]: 
0   2011-12-30
1   2011-12-31
2   2012-01-01
dtype: datetime64[ns]

In [138]: td = s - pd.Series(pd.date_range('2011-12-29', '2011-12-31'))

In [139]: td
Out[139]: 
0   3 days
1   3 days
2   3 days
dtype: timedelta64[ns]

In [140]: td + Minute(15)
Out[140]: 
0   3 days 00:15:00
1   3 days 00:15:00
2   3 days 00:15:00
dtype: 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 [141]: rng + BQuarterEnd()
Out[141]: DatetimeIndex(['2012-03-30', '2012-03-30', '2012-03-30'], dtype='datetime64[ns]', freq=None)

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 [142]: from pandas.tseries.offsets import CustomBusinessDay

In [143]: weekmask_egypt = 'Sun Mon Tue Wed Thu'

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

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

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

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

Let’s map to the weekday names

In [148]: dts = pd.date_range(dt, periods=5, freq=bday_egypt)

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

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

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

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

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

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

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

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

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

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

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

# Define date index with custom offset
In [158]: pd.DatetimeIndex(start='20100101',end='20120101',freq=bmth_us)
Out[158]: 
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')

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.

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. 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, remaining is added to the next business day.

In [159]: bh = BusinessHour()

In [160]: bh
Out[160]: <BusinessHour: BH=09:00-17:00>

# 2014-08-01 is Friday
In [161]: pd.Timestamp('2014-08-01 10:00').weekday()
Out[161]: 4

In [162]: pd.Timestamp('2014-08-01 10:00') + bh
Out[162]: Timestamp('2014-08-01 11:00:00')

# Below example is the same as: pd.Timestamp('2014-08-01 09:00') + bh
In [163]: pd.Timestamp('2014-08-01 08:00') + bh
Out[163]: Timestamp('2014-08-01 10:00:00')

# If the results is on the end time, move to the next business day
In [164]: pd.Timestamp('2014-08-01 16:00') + bh
Out[164]: Timestamp('2014-08-04 09:00:00')

# Remainings are added to the next day
In [165]: pd.Timestamp('2014-08-01 16:30') + bh
Out[165]: Timestamp('2014-08-04 09:30:00')

# Adding 2 business hours
In [166]: pd.Timestamp('2014-08-01 10:00') + BusinessHour(2)
Out[166]: Timestamp('2014-08-01 12:00:00')

# Subtracting 3 business hours
In [167]: pd.Timestamp('2014-08-01 10:00') + BusinessHour(-3)
Out[167]: Timestamp('2014-07-31 15:00:00')

Also, you can specify start and end time by keywords. Argument must be str which has hour:minute representation or datetime.time instance. Specifying seconds, microseconds and nanoseconds as business hour results in ValueError.

In [168]: bh = BusinessHour(start='11:00', end=time(20, 0))

In [169]: bh
Out[169]: <BusinessHour: BH=11:00-20:00>

In [170]: pd.Timestamp('2014-08-01 13:00') + bh
Out[170]: Timestamp('2014-08-01 14:00:00')

In [171]: pd.Timestamp('2014-08-01 09:00') + bh
Out[171]: Timestamp('2014-08-01 12:00:00')

In [172]: pd.Timestamp('2014-08-01 18:00') + bh
Out[172]: Timestamp('2014-08-01 19:00:00')

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 [173]: bh = BusinessHour(start='17:00', end='09:00')

In [174]: bh
Out[174]: <BusinessHour: BH=17:00-09:00>

In [175]: pd.Timestamp('2014-08-01 17:00') + bh
Out[175]: Timestamp('2014-08-01 18:00:00')

In [176]: pd.Timestamp('2014-08-01 23:00') + bh
Out[176]: Timestamp('2014-08-02 00:00:00')

# Although 2014-08-02 is Satuaday,
# it is valid because it starts from 08-01 (Friday).
In [177]: pd.Timestamp('2014-08-02 04:00') + bh
Out[177]: 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 [178]: pd.Timestamp('2014-08-04 04:00') + bh
Out[178]: 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-01 17:00 and 2014-08-04 09:00.

# This adjusts a Timestamp to business hour edge
In [179]: BusinessHour().rollback(pd.Timestamp('2014-08-02 15:00'))
Out[179]: Timestamp('2014-08-01 17:00:00')

In [180]: BusinessHour().rollforward(pd.Timestamp('2014-08-02 15:00'))
Out[180]: Timestamp('2014-08-04 09:00:00')

# It is the same as BusinessHour().apply(pd.Timestamp('2014-08-01 17:00')).
# And it is the same as BusinessHour().apply(pd.Timestamp('2014-08-04 09:00'))
In [181]: BusinessHour().apply(pd.Timestamp('2014-08-02 15:00'))
Out[181]: Timestamp('2014-08-04 10:00:00')

# BusinessDay results (for reference)
In [182]: BusinessHour().rollforward(pd.Timestamp('2014-08-02'))
Out[182]: Timestamp('2014-08-04 09:00:00')

# It is the same as BusinessDay().apply(pd.Timestamp('2014-08-01'))
# The result is the same as rollworward because BusinessDay never overlap.
In [183]: BusinessHour().apply(pd.Timestamp('2014-08-02'))
Out[183]: Timestamp('2014-08-04 10:00:00')

BusinessHour regards Saturday and Sunday as holidays. To use arbitrary holidays, you can use CustomBusinessHour offset, see Custom Business Hour:

Custom Business Hour

New in version 0.18.1.

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 [184]: from pandas.tseries.holiday import USFederalHolidayCalendar

In [185]: bhour_us = CustomBusinessHour(calendar=USFederalHolidayCalendar())

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

In [187]: dt + bhour_us
Out[187]: Timestamp('2014-01-17 16:00:00')

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

You can use keyword arguments suported by either BusinessHour and CustomBusinessDay.

In [189]: bhour_mon = CustomBusinessHour(start='10:00', weekmask='Tue Wed Thu Fri')

# Monday is skipped because it's a holiday, business hour starts from 10:00
In [190]: dt + bhour_mon * 2
Out[190]: Timestamp('2014-01-21 10:00:00')

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
SM semi-month end frequency (15th and end of month)
BM business month end frequency
CBM custom business month end frequency
MS month start frequency
SMS semi-month start frequency (1st and 15th)
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
BH business hour frequency
H hourly frequency
T, min minutely frequency
S secondly frequency
L, ms milliseconds
U, us microseconds
N nanoseconds

Combining Aliases

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

In [191]: pd.date_range(start, periods=5, freq='B')
Out[191]: 
DatetimeIndex(['2011-01-03', '2011-01-04', '2011-01-05', '2011-01-06',
               '2011-01-07'],
              dtype='datetime64[ns]', freq='B')

In [192]: pd.date_range(start, periods=5, freq=BDay())
Out[192]: 
DatetimeIndex(['2011-01-03', '2011-01-04', '2011-01-05', '2011-01-06',
               '2011-01-07'],
              dtype='datetime64[ns]', freq='B')

You can combine together day and intraday offsets:

In [193]: pd.date_range(start, periods=10, freq='2h20min')
Out[193]: 
DatetimeIndex(['2011-01-01 00:00:00', '2011-01-01 02:20:00',
               '2011-01-01 04:40:00', '2011-01-01 07:00:00',
               '2011-01-01 09:20:00', '2011-01-01 11:40:00',
               '2011-01-01 14:00:00', '2011-01-01 16:20:00',
               '2011-01-01 18:40:00', '2011-01-01 21:00:00'],
              dtype='datetime64[ns]', freq='140T')

In [194]: pd.date_range(start, periods=10, freq='1D10U')
Out[194]: 
DatetimeIndex([       '2011-01-01 00:00:00', '2011-01-02 00:00:00.000010',
               '2011-01-03 00:00:00.000020', '2011-01-04 00:00:00.000030',
               '2011-01-05 00:00:00.000040', '2011-01-06 00:00:00.000050',
               '2011-01-07 00:00:00.000060', '2011-01-08 00:00:00.000070',
               '2011-01-09 00:00:00.000080', '2011-01-10 00:00:00.000090'],
              dtype='datetime64[ns]', freq='86400000010U')

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.

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 [195]: pd.Timestamp('2014-01-02') + MonthBegin(n=1)
Out[195]: Timestamp('2014-02-01 00:00:00')

In [196]: pd.Timestamp('2014-01-02') + MonthEnd(n=1)
Out[196]: Timestamp('2014-01-31 00:00:00')

In [197]: pd.Timestamp('2014-01-02') - MonthBegin(n=1)
Out[197]: Timestamp('2014-01-01 00:00:00')

In [198]: pd.Timestamp('2014-01-02') - MonthEnd(n=1)
Out[198]: Timestamp('2013-12-31 00:00:00')

In [199]: pd.Timestamp('2014-01-02') + MonthBegin(n=4)
Out[199]: Timestamp('2014-05-01 00:00:00')

In [200]: pd.Timestamp('2014-01-02') - MonthBegin(n=4)
Out[200]: Timestamp('2013-10-01 00:00:00')

If the given date is on an anchor point, it is moved |n| points forwards or backwards.

In [201]: pd.Timestamp('2014-01-01') + MonthBegin(n=1)
Out[201]: Timestamp('2014-02-01 00:00:00')

In [202]: pd.Timestamp('2014-01-31') + MonthEnd(n=1)
Out[202]: Timestamp('2014-02-28 00:00:00')

In [203]: pd.Timestamp('2014-01-01') - MonthBegin(n=1)
Out[203]: Timestamp('2013-12-01 00:00:00')

In [204]: pd.Timestamp('2014-01-31') - MonthEnd(n=1)
Out[204]: Timestamp('2013-12-31 00:00:00')

In [205]: pd.Timestamp('2014-01-01') + MonthBegin(n=4)
Out[205]: Timestamp('2014-05-01 00:00:00')

In [206]: pd.Timestamp('2014-01-31') - MonthBegin(n=4)
Out[206]: Timestamp('2013-10-01 00:00:00')

For the case when n=0, the date is not moved if on an anchor point, otherwise it is rolled forward to the next anchor point.

In [207]: pd.Timestamp('2014-01-02') + MonthBegin(n=0)
Out[207]: Timestamp('2014-02-01 00:00:00')

In [208]: pd.Timestamp('2014-01-02') + MonthEnd(n=0)
Out[208]: Timestamp('2014-01-31 00:00:00')

In [209]: pd.Timestamp('2014-01-01') + MonthBegin(n=0)
Out[209]: Timestamp('2014-01-01 00:00:00')

In [210]: pd.Timestamp('2014-01-31') + MonthEnd(n=0)
Out[210]: Timestamp('2014-01-31 00:00:00')

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 [211]: from pandas.tseries.holiday import Holiday, USMemorialDay,\
   .....:     AbstractHolidayCalendar, nearest_workday, MO
   .....: 

In [212]: 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 [213]: cal = ExampleCalendar()

In [214]: cal.holidays(datetime(2012, 1, 1), datetime(2012, 12, 31))
Out[214]: DatetimeIndex(['2012-05-28', '2012-07-04', '2012-10-08'], dtype='datetime64[ns]', freq=None)

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.

In [215]: from pandas.tseries.offsets import CDay

In [216]: pd.DatetimeIndex(start='7/1/2012', end='7/10/2012',
   .....:     freq=CDay(calendar=cal)).to_pydatetime()
   .....: 
Out[216]: 
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 [217]: offset = CustomBusinessDay(calendar=cal)

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

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

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

In [221]: datetime(2012, 7, 6) + offset
Out[221]: 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 [222]: AbstractHolidayCalendar.start_date
Out[222]: Timestamp('1970-01-01 00:00:00')

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

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

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

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

In [226]: cal.holidays()
Out[226]: DatetimeIndex(['2012-05-28', '2012-07-04', '2012-10-08'], dtype='datetime64[ns]', freq=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 [227]: from pandas.tseries.holiday import get_calendar, HolidayCalendarFactory,\
   .....:     USLaborDay
   .....: 

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

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

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

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

Resampling

Warning

The interface to .resample has changed in 0.18.0 to be more groupby-like and hence more flexible. See the whatsnew docs for a comparison with prior versions.

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

Starting in version 0.18.1, the resample() function can be used directly from DataFrameGroupBy objects, see the groupby docs.

Note

.resample() is similar to using a .rolling() operation with a time-based offset, see a discussion here

Basics

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

In [243]: ts = pd.Series(np.random.randint(0, 500, len(rng)), index=rng)

In [244]: ts.resample('5Min').sum()
Out[244]: 
2012-01-01    24390
Freq: 5T, dtype: int64

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 [245]: ts.resample('5Min').mean()
Out[245]: 
2012-01-01    243.9
Freq: 5T, dtype: float64

In [246]: ts.resample('5Min').ohlc()
Out[246]: 
            open  high  low  close
2012-01-01   161   495    1    245

In [247]: ts.resample('5Min').max()
Out[247]: 
2012-01-01    495
Freq: 5T, dtype: int64

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 [248]: ts.resample('5Min', closed='right').mean()
Out[248]: 
2011-12-31 23:55:00    161.000000
2012-01-01 00:00:00    244.737374
Freq: 5T, dtype: float64

In [249]: ts.resample('5Min', closed='left').mean()
Out[249]: 
2012-01-01    243.9
Freq: 5T, 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 [250]: ts.resample('5Min').mean() # by default label='right'
Out[250]: 
2012-01-01    243.9
Freq: 5T, dtype: float64

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

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

Up Sampling

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 milliseconds
In [253]: ts[:2].resample('250L').asfreq()
Out[253]: 
2012-01-01 00:00:00.000    161.0
2012-01-01 00:00:00.250      NaN
2012-01-01 00:00:00.500      NaN
2012-01-01 00:00:00.750      NaN
2012-01-01 00:00:01.000    199.0
Freq: 250L, dtype: float64

In [254]: ts[:2].resample('250L').ffill()
Out[254]: 
2012-01-01 00:00:00.000    161
2012-01-01 00:00:00.250    161
2012-01-01 00:00:00.500    161
2012-01-01 00:00:00.750    161
2012-01-01 00:00:01.000    199
Freq: 250L, dtype: int64

In [255]: ts[:2].resample('250L').ffill(limit=2)
Out[255]: 
2012-01-01 00:00:00.000    161.0
2012-01-01 00:00:00.250    161.0
2012-01-01 00:00:00.500    161.0
2012-01-01 00:00:00.750      NaN
2012-01-01 00:00:01.000    199.0
Freq: 250L, dtype: float64

Sparse Resampling

Sparse timeseries are 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 [256]: rng = pd.date_range('2014-1-1', periods=100, freq='D') + pd.Timedelta('1s')

In [257]: ts = pd.Series(range(100), index=rng)

If we want to resample to the full range of the series

In [258]: ts.resample('3T').sum()
Out[258]: 
2014-01-01 00:00:00     0.0
2014-01-01 00:03:00     NaN
2014-01-01 00:06:00     NaN
2014-01-01 00:09:00     NaN
2014-01-01 00:12:00     NaN
2014-01-01 00:15:00     NaN
2014-01-01 00:18:00     NaN
                       ... 
2014-04-09 23:42:00     NaN
2014-04-09 23:45:00     NaN
2014-04-09 23:48:00     NaN
2014-04-09 23:51:00     NaN
2014-04-09 23:54:00     NaN
2014-04-09 23:57:00     NaN
2014-04-10 00:00:00    99.0
Freq: 3T, Length: 47521, dtype: float64

We can instead only resample those groups where we have points as follows:

In [259]: from functools import partial

In [260]: from pandas.tseries.frequencies import to_offset

In [261]: def round(t, freq):
   .....:     freq = to_offset(freq)
   .....:     return pd.Timestamp((t.value // freq.delta.value) * freq.delta.value)
   .....: 

In [262]: ts.groupby(partial(round, freq='3T')).sum()
Out[262]: 
2014-01-01     0
2014-01-02     1
2014-01-03     2
2014-01-04     3
2014-01-05     4
2014-01-06     5
2014-01-07     6
              ..
2014-04-04    93
2014-04-05    94
2014-04-06    95
2014-04-07    96
2014-04-08    97
2014-04-09    98
2014-04-10    99
Length: 100, dtype: int64

Aggregation

Similar to the aggregating API, groupby API, and the window functions API, a Resampler can be selectively resampled.

Resampling a DataFrame, the default will be to act on all columns with the same function.

In [263]: df = pd.DataFrame(np.random.randn(1000, 3),
   .....:                   index=pd.date_range('1/1/2012', freq='S', periods=1000),
   .....:                   columns=['A', 'B', 'C'])
   .....: 

In [264]: r = df.resample('3T')

In [265]: r.mean()
Out[265]: 
                            A         B         C
2012-01-01 00:00:00 -0.220339  0.034854 -0.073757
2012-01-01 00:03:00  0.037070  0.040013  0.053754
2012-01-01 00:06:00 -0.041597 -0.144562 -0.007614
2012-01-01 00:09:00  0.043127 -0.076432 -0.032570
2012-01-01 00:12:00 -0.027609  0.054618  0.056878
2012-01-01 00:15:00 -0.014181  0.043958  0.077734

We can select a specific column or columns using standard getitem.

In [266]: r['A'].mean()
Out[266]: 
2012-01-01 00:00:00   -0.220339
2012-01-01 00:03:00    0.037070
2012-01-01 00:06:00   -0.041597
2012-01-01 00:09:00    0.043127
2012-01-01 00:12:00   -0.027609
2012-01-01 00:15:00   -0.014181
Freq: 3T, Name: A, dtype: float64

In [267]: r[['A','B']].mean()
Out[267]: 
                            A         B
2012-01-01 00:00:00 -0.220339  0.034854
2012-01-01 00:03:00  0.037070  0.040013
2012-01-01 00:06:00 -0.041597 -0.144562
2012-01-01 00:09:00  0.043127 -0.076432
2012-01-01 00:12:00 -0.027609  0.054618
2012-01-01 00:15:00 -0.014181  0.043958

You can pass a list or dict of functions to do aggregation with, outputting a DataFrame:

In [268]: r['A'].agg([np.sum, np.mean, np.std])
Out[268]: 
                           sum      mean       std
2012-01-01 00:00:00 -39.660974 -0.220339  1.033912
2012-01-01 00:03:00   6.672559  0.037070  0.971503
2012-01-01 00:06:00  -7.487453 -0.041597  1.018418
2012-01-01 00:09:00   7.762901  0.043127  1.025842
2012-01-01 00:12:00  -4.969624 -0.027609  0.961649
2012-01-01 00:15:00  -1.418119 -0.014181  0.978847

On a resampled DataFrame, you can pass a list of functions to apply to each column, which produces an aggregated result with a hierarchical index:

In [269]: r.agg([np.sum, np.mean])
Out[269]: 
                             A                    B                    C  \
                           sum      mean        sum      mean        sum   
2012-01-01 00:00:00 -39.660974 -0.220339   6.273786  0.034854 -13.276324   
2012-01-01 00:03:00   6.672559  0.037070   7.202361  0.040013   9.675632   
2012-01-01 00:06:00  -7.487453 -0.041597 -26.021155 -0.144562  -1.370600   
2012-01-01 00:09:00   7.762901  0.043127 -13.757837 -0.076432  -5.862640   
2012-01-01 00:12:00  -4.969624 -0.027609   9.831208  0.054618  10.237970   
2012-01-01 00:15:00  -1.418119 -0.014181   4.395766  0.043958   7.773442   

                               
                         mean  
2012-01-01 00:00:00 -0.073757  
2012-01-01 00:03:00  0.053754  
2012-01-01 00:06:00 -0.007614  
2012-01-01 00:09:00 -0.032570  
2012-01-01 00:12:00  0.056878  
2012-01-01 00:15:00  0.077734  

By passing a dict to aggregate you can apply a different aggregation to the columns of a DataFrame:

In [270]: r.agg({'A' : np.sum,
   .....:        'B' : lambda x: np.std(x, ddof=1)})
   .....: 
Out[270]: 
                             A         B
2012-01-01 00:00:00 -39.660974  1.004756
2012-01-01 00:03:00   6.672559  0.963559
2012-01-01 00:06:00  -7.487453  0.950766
2012-01-01 00:09:00   7.762901  0.949182
2012-01-01 00:12:00  -4.969624  1.093736
2012-01-01 00:15:00  -1.418119  1.028869

The function names can also be strings. In order for a string to be valid it must be implemented on the Resampled object

In [271]: r.agg({'A' : 'sum', 'B' : 'std'})
Out[271]: 
                             A         B
2012-01-01 00:00:00 -39.660974  1.004756
2012-01-01 00:03:00   6.672559  0.963559
2012-01-01 00:06:00  -7.487453  0.950766
2012-01-01 00:09:00   7.762901  0.949182
2012-01-01 00:12:00  -4.969624  1.093736
2012-01-01 00:15:00  -1.418119  1.028869

Furthermore, you can also specify multiple aggregation functions for each column separately.

In [272]: r.agg({'A' : ['sum','std'], 'B' : ['mean','std'] })
Out[272]: 
                             A                   B          
                           sum       std      mean       std
2012-01-01 00:00:00 -39.660974  1.033912  0.034854  1.004756
2012-01-01 00:03:00   6.672559  0.971503  0.040013  0.963559
2012-01-01 00:06:00  -7.487453  1.018418 -0.144562  0.950766
2012-01-01 00:09:00   7.762901  1.025842 -0.076432  0.949182
2012-01-01 00:12:00  -4.969624  0.961649  0.054618  1.093736
2012-01-01 00:15:00  -1.418119  0.978847  0.043958  1.028869

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 [273]: 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 [274]: df
Out[274]: 
              a       date
v d                       
1 2015-01-04  0 2015-01-04
2 2015-01-11  1 2015-01-11
3 2015-01-18  2 2015-01-18
4 2015-01-25  3 2015-01-25
5 2015-02-01  4 2015-02-01

In [275]: df.resample('M', on='date').sum()
Out[275]: 
            a
date         
2015-01-31  6
2015-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 [276]: df.resample('M', level='d').sum()
Out[276]: 
            a
d            
2015-01-31  6
2015-02-28  4

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”.

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

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

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

In [280]: pd.Period('2012-1-1 19:00', freq='5H')
Out[280]: Period('2012-01-01 19:00', '5H')

Adding and subtracting integers from periods shifts the period by its own frequency. Arithmetic is not allowed between Period with different freq (span).

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

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

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

In [284]: p = pd.Period('2012-01', freq='2M')

In [285]: p + 2
Out[285]: Period('2012-05', '2M')

In [286]: p - 1
Out[286]: Period('2011-11', '2M')

In [287]: p == pd.Period('2012-01', freq='3M')
---------------------------------------------------------------------------
IncompatibleFrequency                     Traceback (most recent call last)
<ipython-input-287-ff54ce3238f5> in <module>()
----> 1 p == pd.Period('2012-01', freq='3M')

~/sandbox/pandas/pandas/_libs/period.pyx in pandas._libs.period._Period.__richcmp__ (pandas/_libs/period.c:11842)()

IncompatibleFrequency: Input has different freq=3M from Period(freq=2M)

If Period freq is daily or higher (D, H, T, S, L, U, N), offsets and timedelta-like can be added if the result can have the same freq. Otherwise, ValueError will be raised.

In [288]: p = pd.Period('2014-07-01 09:00', freq='H')

In [289]: p + Hour(2)
Out[289]: Period('2014-07-01 11:00', 'H')

In [290]: p + timedelta(minutes=120)
Out[290]: Period('2014-07-01 11:00', 'H')

In [291]: p + np.timedelta64(7200, 's')
Out[291]: Period('2014-07-01 11:00', 'H')
In [1]: p + Minute(5)
Traceback
   ...
ValueError: Input has different freq from Period(freq=H)

If Period has other freqs, only the same offsets can be added. Otherwise, ValueError will be raised.

In [292]: p = pd.Period('2014-07', freq='M')

In [293]: p + MonthEnd(3)
Out[293]: Period('2014-10', 'M')
In [1]: p + MonthBegin(3)
Traceback
   ...
ValueError: Input has different freq from Period(freq=M)

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

In [294]: pd.Period('2012', freq='A-DEC') - pd.Period('2002', freq='A-DEC')
Out[294]: 10

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 [295]: prng = pd.period_range('1/1/2011', '1/1/2012', freq='M')

In [296]: prng
Out[296]: 
PeriodIndex(['2011-01', '2011-02', '2011-03', '2011-04', '2011-05', '2011-06',
             '2011-07', '2011-08', '2011-09', '2011-10', '2011-11', '2011-12',
             '2012-01'],
            dtype='period[M]', freq='M')

The PeriodIndex constructor can also be used directly:

In [297]: pd.PeriodIndex(['2011-1', '2011-2', '2011-3'], freq='M')
Out[297]: PeriodIndex(['2011-01', '2011-02', '2011-03'], dtype='period[M]', freq='M')

Passing multiplied frequency outputs a sequence of Period which has multiplied span.

In [298]: pd.PeriodIndex(start='2014-01', freq='3M', periods=4)
Out[298]: PeriodIndex(['2014-01', '2014-04', '2014-07', '2014-10'], dtype='period[3M]', freq='3M')

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

In [299]: ps = pd.Series(np.random.randn(len(prng)), prng)

In [300]: ps
Out[300]: 
2011-01   -1.022670
2011-02    1.371155
2011-03    1.035277
2011-04    1.694400
2011-05   -1.659733
2011-06    0.511432
2011-07    0.433176
2011-08   -0.317955
2011-09   -0.517114
2011-10   -0.310466
2011-11    0.543957
2011-12    0.492003
2012-01    0.193420
Freq: M, dtype: float64

PeriodIndex supports addition and subtraction with the same rule as Period.

In [301]: idx = pd.period_range('2014-07-01 09:00', periods=5, freq='H')

In [302]: idx
Out[302]: 
PeriodIndex(['2014-07-01 09:00', '2014-07-01 10:00', '2014-07-01 11:00',
             '2014-07-01 12:00', '2014-07-01 13:00'],
            dtype='period[H]', freq='H')

In [303]: idx + Hour(2)
Out[303]: 
PeriodIndex(['2014-07-01 11:00', '2014-07-01 12:00', '2014-07-01 13:00',
             '2014-07-01 14:00', '2014-07-01 15:00'],
            dtype='period[H]', freq='H')

In [304]: idx = pd.period_range('2014-07', periods=5, freq='M')

In [305]: idx
Out[305]: PeriodIndex(['2014-07', '2014-08', '2014-09', '2014-10', '2014-11'], dtype='period[M]', freq='M')

In [306]: idx + MonthEnd(3)
Out[306]: PeriodIndex(['2014-10', '2014-11', '2014-12', '2015-01', '2015-02'], dtype='period[M]', freq='M')

PeriodIndex has its own dtype named period, refer to Period Dtypes.

Period Dtypes

New in version 0.19.0.

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.

In [307]: pi = pd.period_range('2016-01-01', periods=3, freq='M')

In [308]: pi
Out[308]: PeriodIndex(['2016-01', '2016-02', '2016-03'], dtype='period[M]', freq='M')

In [309]: pi.dtype
Out[309]: period[M]

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():

# change monthly freq to daily freq
In [310]: pi.astype('period[D]')
Out[310]: PeriodIndex(['2016-01-31', '2016-02-29', '2016-03-31'], dtype='period[D]', freq='D')

# convert to DatetimeIndex
In [311]: pi.astype('datetime64[ns]')
Out[311]: DatetimeIndex(['2016-01-01', '2016-02-01', '2016-03-01'], dtype='datetime64[ns]', freq='MS')

# convert to PeriodIndex
In [312]: dti = pd.date_range('2011-01-01', freq='M', periods=3)

In [313]: dti
Out[313]: DatetimeIndex(['2011-01-31', '2011-02-28', '2011-03-31'], dtype='datetime64[ns]', freq='M')

In [314]: dti.astype('period[M]')
Out[314]: PeriodIndex(['2011-01', '2011-02', '2011-03'], dtype='period[M]', freq='M')

PeriodIndex Partial String Indexing

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 [315]: ps['2011-01']
Out[315]: -1.022669594890105

In [316]: ps[datetime(2011, 12, 25):]
Out[316]: 
2011-12    0.492003
2012-01    0.193420
Freq: M, dtype: float64

In [317]: ps['10/31/2011':'12/31/2011']
Out[317]: 
2011-10   -0.310466
2011-11    0.543957
2011-12    0.492003
Freq: M, dtype: float64

Passing a string representing a lower frequency than PeriodIndex returns partial sliced data.

In [318]: ps['2011']
Out[318]: 
2011-01   -1.022670
2011-02    1.371155
2011-03    1.035277
2011-04    1.694400
2011-05   -1.659733
2011-06    0.511432
2011-07    0.433176
2011-08   -0.317955
2011-09   -0.517114
2011-10   -0.310466
2011-11    0.543957
2011-12    0.492003
Freq: M, dtype: float64

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

In [320]: dfp
Out[320]: 
                         A
2013-01-01 09:00  0.197720
2013-01-01 09:01 -0.284769
2013-01-01 09:02  0.061491
2013-01-01 09:03  1.630257
2013-01-01 09:04  2.042442
2013-01-01 09:05 -0.804392
2013-01-01 09:06  0.212760
...                    ...
2013-01-01 18:53  0.150586
2013-01-01 18:54 -0.679569
2013-01-01 18:55 -0.910216
2013-01-01 18:56 -0.413168
2013-01-01 18:57 -0.247752
2013-01-01 18:58  1.590875
2013-01-01 18:59 -2.005294

[600 rows x 1 columns]

In [321]: dfp['2013-01-01 10H']
Out[321]: 
                         A
2013-01-01 10:00 -0.569936
2013-01-01 10:01 -1.179183
2013-01-01 10:02 -0.838602
2013-01-01 10:03 -1.727539
2013-01-01 10:04  1.334027
2013-01-01 10:05  0.417423
2013-01-01 10:06 -0.221189
...                    ...
2013-01-01 10:53 -0.375925
2013-01-01 10:54  0.212750
2013-01-01 10:55 -0.592417
2013-01-01 10:56 -0.466064
2013-01-01 10:57 -1.715347
2013-01-01 10:58 -0.634913
2013-01-01 10:59 -0.809471

[60 rows x 1 columns]

As with DatetimeIndex, the endpoints will be included in the result. The example below slices data starting from 10:00 to 11:59.

In [322]: dfp['2013-01-01 10H':'2013-01-01 11H']
Out[322]: 
                         A
2013-01-01 10:00 -0.569936
2013-01-01 10:01 -1.179183
2013-01-01 10:02 -0.838602
2013-01-01 10:03 -1.727539
2013-01-01 10:04  1.334027
2013-01-01 10:05  0.417423
2013-01-01 10:06 -0.221189
...                    ...
2013-01-01 11:53  0.616198
2013-01-01 11:54  2.843156
2013-01-01 11:55  0.572537
2013-01-01 11:56  1.709706
2013-01-01 11:57 -0.205490
2013-01-01 11:58  1.759719
2013-01-01 11:59 -1.181485

[120 rows x 1 columns]

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 [323]: p = pd.Period('2011', freq='A-DEC')

In [324]: p
Out[324]: 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 [325]: p.asfreq('M', how='start')
Out[325]: Period('2011-01', 'M')

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

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

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

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

In [330]: p.asfreq('A-NOV')
Out[330]: 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 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.

Q-DEC define regular calendar quarters:

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

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

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

Q-MAR defines fiscal year end in March:

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

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

In [336]: p.asfreq('D', 'e')
Out[336]: 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 [337]: rng = pd.date_range('1/1/2012', periods=5, freq='M')

In [338]: ts = pd.Series(np.random.randn(len(rng)), index=rng)

In [339]: ts
Out[339]: 
2012-01-31    2.167674
2012-02-29   -1.505130
2012-03-31    1.005802
2012-04-30    0.481525
2012-05-31   -0.352151
Freq: M, dtype: float64

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

In [341]: ps
Out[341]: 
2012-01    2.167674
2012-02   -1.505130
2012-03    1.005802
2012-04    0.481525
2012-05   -0.352151
Freq: M, dtype: float64

In [342]: ps.to_timestamp()
Out[342]: 
2012-01-01    2.167674
2012-02-01   -1.505130
2012-03-01    1.005802
2012-04-01    0.481525
2012-05-01   -0.352151
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 [343]: ps.to_timestamp('D', how='s')
Out[343]: 
2012-01-01    2.167674
2012-02-01   -1.505130
2012-03-01    1.005802
2012-04-01    0.481525
2012-05-01   -0.352151
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 [344]: prng = pd.period_range('1990Q1', '2000Q4', freq='Q-NOV')

In [345]: ts = pd.Series(np.random.randn(len(prng)), prng)

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

In [347]: ts.head()
Out[347]: 
1990-03-01 09:00   -0.608988
1990-06-01 09:00    0.412294
1990-09-01 09:00   -0.715938
1990-12-01 09:00    1.297773
1991-03-01 09:00   -2.260765
Freq: H, dtype: float64

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 [348]: span = pd.period_range('1215-01-01', '1381-01-01', freq='D')

In [349]: span
Out[349]: 
PeriodIndex(['1215-01-01', '1215-01-02', '1215-01-03', '1215-01-04',
             '1215-01-05', '1215-01-06', '1215-01-07', '1215-01-08',
             '1215-01-09', '1215-01-10',
             ...
             '1380-12-23', '1380-12-24', '1380-12-25', '1380-12-26',
             '1380-12-27', '1380-12-28', '1380-12-29', '1380-12-30',
             '1380-12-31', '1381-01-01'],
            dtype='period[D]', length=60632, freq='D')

To convert from a int64 based YYYYMMDD representation.

In [350]: s = pd.Series([20121231, 20141130, 99991231])

In [351]: s
Out[351]: 
0    20121231
1    20141130
2    99991231
dtype: int64

In [352]: def conv(x):
   .....:     return pd.Period(year = x // 10000, month = x//100 % 100, day = x%100, freq='D')
   .....: 

In [353]: s.apply(conv)
Out[353]: 
0   2012-12-31
1   2014-11-30
2   9999-12-31
dtype: object

In [354]: s.apply(conv)[2]
Out[354]: Period('9999-12-31', 'D')

These can easily be converted to a PeriodIndex

In [355]: span = pd.PeriodIndex(s.apply(conv))

In [356]: span
Out[356]: PeriodIndex(['2012-12-31', '2014-11-30', '9999-12-31'], dtype='period[D]', freq='D')

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.

Working with Time Zones

By default, pandas objects are time zone unaware:

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

In [358]: rng.tz is None
Out[358]: 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 [359]: rng_pytz = pd.date_range('3/6/2012 00:00', periods=10, freq='D',
   .....:                          tz='Europe/London')
   .....: 

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

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

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

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

In [364]: rng_utc.tz
Out[364]: 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 [365]: tz_pytz = pytz.timezone('Europe/London')

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

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

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

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

In [370]: rng_dateutil.tz == tz_dateutil
Out[370]: 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 [371]: ts = pd.Series(np.random.randn(len(rng)), rng)

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

In [373]: ts_utc
Out[373]: 
2012-03-06 00:00:00+00:00    0.679135
2012-03-07 00:00:00+00:00    0.345668
2012-03-08 00:00:00+00:00   -1.143903
2012-03-09 00:00:00+00:00    0.487087
2012-03-10 00:00:00+00:00   -1.421073
2012-03-11 00:00:00+00:00   -0.327463
2012-03-12 00:00:00+00:00    0.169899
2012-03-13 00:00:00+00:00    0.867568
2012-03-14 00:00:00+00:00   -0.834122
2012-03-15 00:00:00+00:00   -1.698494
2012-03-16 00:00:00+00:00    0.974717
2012-03-17 00:00:00+00:00    0.966771
2012-03-18 00:00:00+00:00   -0.754168
2012-03-19 00:00:00+00:00   -1.434246
2012-03-20 00:00:00+00:00    0.848935
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 [374]: ts_utc.tz_convert('US/Eastern')
Out[374]: 
2012-03-05 19:00:00-05:00    0.679135
2012-03-06 19:00:00-05:00    0.345668
2012-03-07 19:00:00-05:00   -1.143903
2012-03-08 19:00:00-05:00    0.487087
2012-03-09 19:00:00-05:00   -1.421073
2012-03-10 19:00:00-05:00   -0.327463
2012-03-11 20:00:00-04:00    0.169899
2012-03-12 20:00:00-04:00    0.867568
2012-03-13 20:00:00-04:00   -0.834122
2012-03-14 20:00:00-04:00   -1.698494
2012-03-15 20:00:00-04:00    0.974717
2012-03-16 20:00:00-04:00    0.966771
2012-03-17 20:00:00-04:00   -0.754168
2012-03-18 20:00:00-04:00   -1.434246
2012-03-19 20:00:00-04:00    0.848935
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.

Warning

It is incorrect to pass a timezone directly into the datetime.datetime constructor (e.g., datetime.datetime(2011, 1, 1, tz=timezone('US/Eastern')). Instead, the datetime needs to be localized using the the localize method on the timezone.

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 [375]: rng_eastern = rng_utc.tz_convert('US/Eastern')

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

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

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

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

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

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

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

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

Localization of Timestamp functions just like DatetimeIndex and Series:

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

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

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

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

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

In [387]: result = eastern + berlin

In [388]: result
Out[388]: 
2012-03-06 00:00:00+00:00    1.358269
2012-03-07 00:00:00+00:00    0.691336
2012-03-08 00:00:00+00:00   -2.287805
2012-03-09 00:00:00+00:00    0.974174
2012-03-10 00:00:00+00:00   -2.842146
2012-03-11 00:00:00+00:00   -0.654926
2012-03-12 00:00:00+00:00    0.339798
2012-03-13 00:00:00+00:00    1.735136
2012-03-14 00:00:00+00:00   -1.668245
2012-03-15 00:00:00+00:00   -3.396988
2012-03-16 00:00:00+00:00    1.949435
2012-03-17 00:00:00+00:00    1.933541
2012-03-18 00:00:00+00:00   -1.508335
2012-03-19 00:00:00+00:00   -2.868493
2012-03-20 00:00:00+00:00    1.697870
Freq: D, dtype: float64

In [389]: result.index
Out[389]: 
DatetimeIndex(['2012-03-06', '2012-03-07', '2012-03-08', '2012-03-09',
               '2012-03-10', '2012-03-11', '2012-03-12', '2012-03-13',
               '2012-03-14', '2012-03-15', '2012-03-16', '2012-03-17',
               '2012-03-18', '2012-03-19', '2012-03-20'],
              dtype='datetime64[ns, UTC]', freq='D')

To remove timezone from tz-aware DatetimeIndex, use tz_localize(None) or tz_convert(None). tz_localize(None) will remove timezone holding local time representations. tz_convert(None) will remove timezone after converting to UTC time.

In [390]: didx = pd.DatetimeIndex(start='2014-08-01 09:00', freq='H', periods=10, tz='US/Eastern')

In [391]: didx
Out[391]: 
DatetimeIndex(['2014-08-01 09:00:00-04:00', '2014-08-01 10:00:00-04:00',
               '2014-08-01 11:00:00-04:00', '2014-08-01 12:00:00-04:00',
               '2014-08-01 13:00:00-04:00', '2014-08-01 14:00:00-04:00',
               '2014-08-01 15:00:00-04:00', '2014-08-01 16:00:00-04:00',
               '2014-08-01 17:00:00-04:00', '2014-08-01 18:00:00-04:00'],
              dtype='datetime64[ns, US/Eastern]', freq='H')

In [392]: didx.tz_localize(None)
Out[392]: 
DatetimeIndex(['2014-08-01 09:00:00', '2014-08-01 10:00:00',
               '2014-08-01 11:00:00', '2014-08-01 12:00:00',
               '2014-08-01 13:00:00', '2014-08-01 14:00:00',
               '2014-08-01 15:00:00', '2014-08-01 16:00:00',
               '2014-08-01 17:00:00', '2014-08-01 18:00:00'],
              dtype='datetime64[ns]', freq='H')

In [393]: didx.tz_convert(None)
Out[393]: 
DatetimeIndex(['2014-08-01 13:00:00', '2014-08-01 14:00:00',
               '2014-08-01 15:00:00', '2014-08-01 16:00:00',
               '2014-08-01 17:00:00', '2014-08-01 18:00:00',
               '2014-08-01 19:00:00', '2014-08-01 20:00:00',
               '2014-08-01 21:00:00', '2014-08-01 22:00:00'],
              dtype='datetime64[ns]', freq='H')

# tz_convert(None) is identical with tz_convert('UTC').tz_localize(None)
In [394]: didx.tz_convert('UCT').tz_localize(None)
Out[394]: 
DatetimeIndex(['2014-08-01 13:00:00', '2014-08-01 14:00:00',
               '2014-08-01 15:00:00', '2014-08-01 16:00:00',
               '2014-08-01 17:00:00', '2014-08-01 18:00:00',
               '2014-08-01 19:00:00', '2014-08-01 20:00:00',
               '2014-08-01 21:00:00', '2014-08-01 22:00:00'],
              dtype='datetime64[ns]', freq='H')

Ambiguous Times when Localizing

In some cases, localize cannot determine the DST and non-DST hours when there are duplicates. This often happens when reading files or database records that simply duplicate the hours. Passing ambiguous='infer' (infer_dst argument in prior releases) into tz_localize will attempt to determine the right offset. Below the top example will fail as it contains ambiguous times and the bottom will infer the right offset.

In [395]: rng_hourly = pd.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'])
   .....: 

This will fail as there are ambiguous times

In [2]: rng_hourly.tz_localize('US/Eastern')
AmbiguousTimeError: Cannot infer dst time from Timestamp('2011-11-06 01:00:00'), try using the 'ambiguous' argument

Infer the ambiguous times

In [396]: rng_hourly_eastern = rng_hourly.tz_localize('US/Eastern', ambiguous='infer')

In [397]: rng_hourly_eastern.tolist()
Out[397]: 
[Timestamp('2011-11-06 00:00:00-0400', tz='US/Eastern'),
 Timestamp('2011-11-06 01:00:00-0400', tz='US/Eastern'),
 Timestamp('2011-11-06 01:00:00-0500', tz='US/Eastern'),
 Timestamp('2011-11-06 02:00:00-0500', tz='US/Eastern'),
 Timestamp('2011-11-06 03:00:00-0500', tz='US/Eastern')]

In addition to ‘infer’, there are several other arguments supported. Passing an array-like of bools or 0s/1s where True represents a DST hour and False a non-DST hour, allows for distinguishing more than one DST transition (e.g., if you have multiple records in a database each with their own DST transition). Or passing ‘NaT’ will fill in transition times with not-a-time values. These methods are available in the DatetimeIndex constructor as well as tz_localize.

In [398]: rng_hourly_dst = np.array([1, 1, 0, 0, 0])

In [399]: rng_hourly.tz_localize('US/Eastern', ambiguous=rng_hourly_dst).tolist()
Out[399]: 
[Timestamp('2011-11-06 00:00:00-0400', tz='US/Eastern'),
 Timestamp('2011-11-06 01:00:00-0400', tz='US/Eastern'),
 Timestamp('2011-11-06 01:00:00-0500', tz='US/Eastern'),
 Timestamp('2011-11-06 02:00:00-0500', tz='US/Eastern'),
 Timestamp('2011-11-06 03:00:00-0500', tz='US/Eastern')]

In [400]: rng_hourly.tz_localize('US/Eastern', ambiguous='NaT').tolist()
Out[400]: 
[Timestamp('2011-11-06 00:00:00-0400', tz='US/Eastern'),
 NaT,
 NaT,
 Timestamp('2011-11-06 02:00:00-0500', tz='US/Eastern'),
 Timestamp('2011-11-06 03:00:00-0500', tz='US/Eastern')]

In [401]: didx = pd.DatetimeIndex(start='2014-08-01 09:00', freq='H', periods=10, tz='US/Eastern')

In [402]: didx
Out[402]: 
DatetimeIndex(['2014-08-01 09:00:00-04:00', '2014-08-01 10:00:00-04:00',
               '2014-08-01 11:00:00-04:00', '2014-08-01 12:00:00-04:00',
               '2014-08-01 13:00:00-04:00', '2014-08-01 14:00:00-04:00',
               '2014-08-01 15:00:00-04:00', '2014-08-01 16:00:00-04:00',
               '2014-08-01 17:00:00-04:00', '2014-08-01 18:00:00-04:00'],
              dtype='datetime64[ns, US/Eastern]', freq='H')

In [403]: didx.tz_localize(None)
Out[403]: 
DatetimeIndex(['2014-08-01 09:00:00', '2014-08-01 10:00:00',
               '2014-08-01 11:00:00', '2014-08-01 12:00:00',
               '2014-08-01 13:00:00', '2014-08-01 14:00:00',
               '2014-08-01 15:00:00', '2014-08-01 16:00:00',
               '2014-08-01 17:00:00', '2014-08-01 18:00:00'],
              dtype='datetime64[ns]', freq='H')

In [404]: didx.tz_convert(None)
Out[404]: 
DatetimeIndex(['2014-08-01 13:00:00', '2014-08-01 14:00:00',
               '2014-08-01 15:00:00', '2014-08-01 16:00:00',
               '2014-08-01 17:00:00', '2014-08-01 18:00:00',
               '2014-08-01 19:00:00', '2014-08-01 20:00:00',
               '2014-08-01 21:00:00', '2014-08-01 22:00:00'],
              dtype='datetime64[ns]', freq='H')

# tz_convert(None) is identical with tz_convert('UTC').tz_localize(None)
In [405]: didx.tz_convert('UCT').tz_localize(None)
Out[405]: 
DatetimeIndex(['2014-08-01 13:00:00', '2014-08-01 14:00:00',
               '2014-08-01 15:00:00', '2014-08-01 16:00:00',
               '2014-08-01 17:00:00', '2014-08-01 18:00:00',
               '2014-08-01 19:00:00', '2014-08-01 20:00:00',
               '2014-08-01 21:00:00', '2014-08-01 22:00:00'],
              dtype='datetime64[ns]', freq='H')

TZ aware Dtypes

New in version 0.17.0.

Series/DatetimeIndex with a timezone naive value are represented with a dtype of datetime64[ns].

In [406]: s_naive = pd.Series(pd.date_range('20130101',periods=3))

In [407]: s_naive
Out[407]: 
0   2013-01-01
1   2013-01-02
2   2013-01-03
dtype: datetime64[ns]

Series/DatetimeIndex with a timezone aware value are represented with a dtype of datetime64[ns, tz].

In [408]: s_aware = pd.Series(pd.date_range('20130101',periods=3,tz='US/Eastern'))

In [409]: s_aware
Out[409]: 
0   2013-01-01 00:00:00-05:00
1   2013-01-02 00:00:00-05:00
2   2013-01-03 00:00:00-05:00
dtype: datetime64[ns, US/Eastern]

Both of these Series can be manipulated via the .dt accessor, see here.

For example, to localize and convert a naive stamp to timezone aware.

In [410]: s_naive.dt.tz_localize('UTC').dt.tz_convert('US/Eastern')
Out[410]: 
0   2012-12-31 19:00:00-05:00
1   2013-01-01 19:00:00-05:00
2   2013-01-02 19:00:00-05:00
dtype: datetime64[ns, US/Eastern]

Further more you can .astype(...) timezone aware (and naive). This operation is effectively a localize AND convert on a naive stamp, and a convert on an aware stamp.

# localize and convert a naive timezone
In [411]: s_naive.astype('datetime64[ns, US/Eastern]')
Out[411]: 
0   2012-12-31 19:00:00-05:00
1   2013-01-01 19:00:00-05:00
2   2013-01-02 19:00:00-05:00
dtype: datetime64[ns, US/Eastern]

# make an aware tz naive
In [412]: s_aware.astype('datetime64[ns]')
Out[412]: 
0   2013-01-01 05:00:00
1   2013-01-02 05:00:00
2   2013-01-03 05:00:00
dtype: datetime64[ns]

# convert to a new timezone
In [413]: s_aware.astype('datetime64[ns, CET]')
Out[413]: 
0   2013-01-01 06:00:00+01:00
1   2013-01-02 06:00:00+01:00
2   2013-01-03 06:00:00+01:00
dtype: datetime64[ns, CET]

Note

Using the .values accessor on a Series, returns an numpy array of the data. These values are converted to UTC, as numpy does not currently support timezones (even though it is printing in the local timezone!).

In [414]: s_naive.values
Out[414]: 
array(['2013-01-01T00:00:00.000000000', '2013-01-02T00:00:00.000000000',
       '2013-01-03T00:00:00.000000000'], dtype='datetime64[ns]')

In [415]: s_aware.values
Out[415]: 
array(['2013-01-01T05:00:00.000000000', '2013-01-02T05:00:00.000000000',
       '2013-01-03T05:00:00.000000000'], dtype='datetime64[ns]')

Further note that once converted to a numpy array these would lose the tz tenor.

In [416]: pd.Series(s_aware.values)
Out[416]: 
0   2013-01-01 05:00:00
1   2013-01-02 05:00:00
2   2013-01-03 05:00:00
dtype: datetime64[ns]

However, these can be easily converted

In [417]: pd.Series(s_aware.values).dt.tz_localize('UTC').dt.tz_convert('US/Eastern')
Out[417]: 
0   2013-01-01 00:00:00-05:00
1   2013-01-02 00:00:00-05:00
2   2013-01-03 00:00:00-05:00
dtype: datetime64[ns, US/Eastern]
Scroll To Top